I am new to C++. While trying sample polymorphism code, I found that base class virtual function definition in derived class is possible only when defined within the derived class or outside with declaration in derived class.
Following code gives error:
class B
{
public:
virtual void f();
};
void B::f() {
std::cout<<"B::f";
}
class D : public B
{
public:
void f2() {int b;}
};
// error: no "void D::f()" member function declared in class "D"
void D::f() {
std::cout<<"D::F";
}
It works if I declare f() inside D. I was wondering why do I need to explicitly declare the function again when it is already declared in Base class. The compiler can get the signature from Base class right?
Thanks in advance..
You can’t add members to a class outside of the class definition. If you want
Dto have an override forB::fthen you have to declare it inside the class definition. Those are the rules.Declaring a member in a base class doesn’t automatically give derived classes an identical member. Inheriting from the base gives the derived class all the members of the base class so you can choose whether to override, hide or add to the base classes members but you have to indicate a choice to override in the class definition by declaring the overriding function.