Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

call to pure virtual function from base class constructor

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?

like image 245
herzl shemuelian Avatar asked Dec 25 '11 15:12

herzl shemuelian


People also ask

Can you call a pure virtual function in a constructor?

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.

Can a base class call pure virtual function?

C++ corner case: You can implement pure virtual functions in the base class.

How do you call a virtual function through a base class reference?

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.

Can a pure virtual class have a constructor?

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.


1 Answers

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.

like image 77
a1ex07 Avatar answered Oct 13 '22 05:10

a1ex07