I have a base class MyBase that contains a pure virtual function:
void PrintStartMessage() = 0
I want each derived class to call it in their constructor
then I put it in base class(MyBase
) constructor
class MyBase { public: virtual void PrintStartMessage() =0; MyBase() { PrintStartMessage(); } }; class Derived:public MyBase { public: void PrintStartMessage(){ } }; void main() { Derived derived; }
but I get a linker error.
this is error message : 1>------ Build started: Project: s1, Configuration: Debug Win32 ------ 1>Compiling... 1>s1.cpp 1>Linking... 1>s1.obj : error LNK2019: unresolved external symbol "public: virtual void __thiscall MyBase::PrintStartMessage(void)" (?PrintStartMessage@MyBase@@UAEXXZ) referenced in function "public: __thiscall MyBase::MyBase(void)" (??0MyBase@@QAE@XZ) 1>C:\Users\Shmuelian\Documents\Visual Studio 2008\Projects\s1\Debug\s1.exe : fatal error LNK1120: 1 unresolved externals 1>s1 - 2 error(s), 0 warning(s)
I want force to all derived classes to...
A- implement it B- call it in their constructor
How I must do it?
Pure virtual functions must not be called from a C++ constructor. As a general rule, you should never call any kind of virtual function in a constructor or destructor because those calls will never go to a more derived class than the currently executing constructor or destructor.
C++ corner case: You can implement pure virtual functions in the base class.
A virtual function is a member function that you expect to be redefined in derived classes. When you refer to a derived class object using a pointer or a reference to the base class, you can call a virtual function for that object and execute the derived class's version of the function.
A class with one (or more) virtual pure functions is abstract, and it can't be used to create a new object, so it doesn't have a constructor.
There are many articles that explain why you should never call virtual functions in constructor and destructor in C++. Take a look here and here for details what happens behind the scene during such calls.
In short, objects are constructed from the base up to the derived. So when you try to call a virtual function from the base class constructor, overriding from derived classes hasn't yet happened because the derived constructors haven't been called yet.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With