Implementing C ++ virtual functions outside the class

I am new to C ++. Having tried a sample polymorphism code, I found that the definition of a virtual function of a base class in a derived class is possible only when defined inside the derived class or externally with a declaration in the derived class.

The following code gives an 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 I need to explicitly declare the function again when it is already declared in the base class. Can a compiler get a signature from a base class?

Thanks in advance.

+7
source share
3 answers

You cannot add members to a class outside the class definition. If you want D have an override for B::f , then you must declare it inside the class definition. These are the rules.

Declaring an element in a base class does not automatically give derived classes the same member. Inheriting from the base gives the derived class all the members of the base class, so you can select, override, hide, or add to the elements of the base classes, but you must specify what you want to override in the class definition by declaring the override function.

+8
source

Even if D comes from B, and therefore you can call f () on an instance of D, this does not mean that you do not need to put the declaration in the header.

Any function you implement must be explicitly declared in the header.

You do not need, however, to put your implementation there. Just

 class D : public B { public: /*virtual*/ void f(); }; 

and you can choose whether to include the word "virtual"

+3
source

In C ++, the definition of your class tells the compiler that performs the functions of the class. Therefore, if you want to write the function "D :: f ()", you must have f () in the class definition for D.

The fact that the function "B :: f ()" is defined in the base class does not matter. Each class definition must explicitly declare the functions that it implements.

+1
source

All Articles