compilation error regarding name hiding ,override and virtual table

126 views Asked by At

I was playing c++ rule. I hit an error but i can't explain it. please help to explain why the compilation error happen. BTW, I am not interesting at fixing the problem. Thanks

Q1 why the name hiding doesnt work in the case? for example, if we remove lineA's keyword virtual.the compilation will works

Q2 after added a function in case2, the compilation goes through.

please help explain Q1 and Q2.

#include

using namespace std;

class base
{
   public:
      virtual int func() // lineA
      {
         cout << "vfunc in base class\n";
         return 0;
      }
};

class derived: public base
{
   public:
      double func()
      {
         cout << "vfunc in derived class\n";
         return 0;
      }
};

int main()
{
   return 0;
}

output:

main.cpp:18:14: error: conflicting return type specified for 'virtual double derived::func()'
       double func()
              ^
main.cpp:8:19: error:   overriding 'virtual int base::func()'
       virtual int func()

case 2:

#include <iostream>

using namespace std;

class base
{
   public:
      virtual int func()
      {
         cout << "vfunc in base class\n";
         return 0;
      }
     // new added 
      virtual double func(int)
      {
          return 0.0;
      }
};

class derived: public base
{
   public:
      double func(int)
      {
         cout << "vfunc in derived class\n";
         return 0;
      }
};

int main()
{
   return 0;
}             ^
2

There are 2 answers

0
Alan Stokes On

When you override a function, your new implementation must be callable whenever the original was. The base function here returns an int. That means any caller will expect an int.

The error occurs because your overriding function is returning a double instead of an int.

0
j.karlsson On

Well as the compiler error states you have defined different return types for func(). You may think that this should be handeled by C++ overloading, but overloading can only be done on input parameters not on return values. For example:

class base
{
   public:
      virtual int func(int param)
      {
         cout << "vfunc in base class\n";
         return 0;
      }
};

class derived: public base
{
   public:
      double func(double param)
      {
         cout << "vfunc in derived class\n";
         return 0;
      }
};

In this code func is overloaded in derived since it has another type for the input param.