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;
} ^
When you override a function, your new implementation must be callable whenever the original was. The
base
function here returns anint
. That means any caller will expect anint
.The error occurs because your overriding function is returning a
double
instead of anint
.