call to pure virtual function from base class constructor

calling pure virtual function from base class
private virtual function c++
c++ virtual function
base class object calling derived function
c++ override non virtual function
how to call a function in a constructor c++
how to call base class method from derived class in c++
c : virtual function not called

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?


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.

C++ Abstract Class: constructor yes or no?, How do you call a virtual function in base class? You can’t do it the way you imagine because you cannot call derived virtual functions from within the base class constructor—the object is not yet of the derived type. But you don’t need to do this. Calling PrintStartMessage after MyBase construction. Let’s assume that you want to do something like this:


Trying to call a pure abstract method from a derived while that object is still being constructed is unsafe. It's like trying to fill gas into a car but that car is still on the assembly line and the gas tank hasn't been put in yet.

The closest you can get to doing something like that is to fully construct your object first and then calling the method after:

template <typename T>
T construct_and_print()
{
  T obj;
  obj.PrintStartMessage();

  return obj;
}

int main()
{
    Derived derived = construct_and_print<Derived>();
}

Can I call a base class's virtual function if I'm overriding it?, discussion __purecall , we saw that you can declare a pure virtual function with the = 0 syntax, and if you try to call one of these functions from the base class, Member functions can be called from a constructor (or destructor) So a call to the virtual method in the constructor will call the Base class' virtual method. Or if it has no implementation at that level, it'll produce a pure virtual method call. Once Base is fully constructed, the compiler starts building Derived class, and overrides the method pointers to point Derived class' implementation.


You can't do it the way you imagine because you cannot call derived virtual functions from within the base class constructor—the object is not yet of the derived type. But you don't need to do this.

Calling PrintStartMessage after MyBase construction

Let's assume that you want to do something like this:

class MyBase {
public:
    virtual void PrintStartMessage() = 0;
    MyBase() {
        printf("Doing MyBase initialization...\n");
        PrintStartMessage(); // ⚠ UB: pure virtual function call ⚠
    }
};

class Derived : public MyBase {
public:
    virtual void PrintStartMessage() { printf("Starting Derived!\n"); }
};

That is, the desired output is:

Doing MyBase initialization...
Starting Derived!

But this is exactly what constructors are for! Just scrap the virtual function and make the constructor of Derived do the job:

class MyBase {
public:
    MyBase() { printf("Doing MyBase initialization...\n"); }
};

class Derived : public MyBase {
public:
    Derived() { printf("Starting Derived!\n"); }
};

The output is, well, what we would expect:

Doing MyBase initialization...
Starting Derived!

This doesn't enforce the derived classes to explicitly implement the PrintStartMessage functionality though. But on the other hand, think twice whether it is at all necessary, as they otherwise can always provide an empty implementation anyway.

Calling PrintStartMessage before MyBase construction

As said above, if you want to call PrintStartMessage before the Derived has been constructed, you cannot accomplish this because there is no yet a Derived object for PrintStartMessage to be called upon. It would make no sense to require PrintStartMessage to be a non-static member because it would have no access to any of the Derived data members.

A static function with factory function

Alternatively we can make it a static member like so:

class MyBase {
public:
    MyBase() {
        printf("Doing MyBase initialization...\n");
    }
};

class Derived : public MyBase {
public:
    static void PrintStartMessage() { printf("Derived specific message.\n"); }
};

A natural question arises of how it will be called?

There are two solution I can see: one is similar to that of @greatwolf, where you have to call it manually. But now, since it is a static member, you can call it before an instance of MyBase has been constructed:

template<class T>
T print_and_construct() {
    T::PrintStartMessage();
    return T();
}

int main() {
    Derived derived = print_and_construct<Derived>();
}

The output will be

Derived specific message.
Doing MyBase initialization...

This approach does force all derived classes to implement PrintStartMessage. Unfortunately it's only true when we construct them with our factory function... which is a huge downside of this solution.

The second solution is to resort to the Curiously Recurring Template Pattern (CRTP). By telling MyBase the complete object type at compile time it can do the call from within the constructor:

template<class T>
class MyBase {
public:
    MyBase() {
        T::PrintStartMessage();
        printf("Doing MyBase initialization...\n");
    }
};

class Derived : public MyBase<Derived> {
public:
    static void PrintStartMessage() { printf("Derived specific message.\n"); }
};

The output is as expected, without the need of using a dedicated factory function.

Accessing MyBase from within PrintStartMessage with CRTP

While MyBase is being executed, its already OK to access its members. We can make PrintStartMessage be able to access the MyBase that has called it:

template<class T>
class MyBase {
public:
    MyBase() {
        T::PrintStartMessage(this);
        printf("Doing MyBase initialization...\n");
    }
};

class Derived : public MyBase<Derived> {
public:
    static void PrintStartMessage(MyBase<Derived> *p) {
        // We can access p here
        printf("Derived specific message.\n");
    }
};

The following is also valid and very frequently used, albeit a bit dangerous:

template<class T>
class MyBase {
public:
    MyBase() {
        static_cast<T*>(this)->PrintStartMessage();
        printf("Doing MyBase initialization...\n");
    }
};

class Derived : public MyBase<Derived> {
public:
    void PrintStartMessage() {
        // We can access *this member functions here, but only those from MyBase
        // or those of Derived who follow this same restriction. I.e. no
        // Derived data members access as they have not yet been constructed.
        printf("Derived specific message.\n");
    }
};
No templates solution—redesign

Yet another option is to redesign your code a little. IMO this one is actually the preferred solution if you absolutely have to call an overridden PrintStartMessage from within MyBase construction.

This proposal is to separate Derived from MyBase, as follows:

class ICanPrintStartMessage {
public:
    virtual ~ICanPrintStartMessage() {}
    virtual void PrintStartMessage() = 0;
};

class MyBase {
public:
    MyBase(ICanPrintStartMessage *p) : _p(p) {
        _p->PrintStartMessage();
        printf("Doing MyBase initialization...\n");
    }

    ICanPrintStartMessage *_p;
};

class Derived : public ICanPrintStartMessage {
public:
    virtual void PrintStartMessage() { printf("Starting Derived!!!\n"); }
};

You initialize MyBase as follows:

int main() {
    Derived d;
    MyBase b(&d);
}

Pure Virtual Functions and Abstract Classes in C++, When my base class's constructor calls a virtual function on its this object, why pure virtual ) but Shape::print() could, if we were guaranteed no derived class  Pure virtual functions must not be called from a C++ constructor. Pure virtual function call in 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.


You shouldn't call a virtual function in a constructor. Period. You'll have to find some workaround, like making PrintStartMessage non-virtual and putting the call explicitly in every constructor.

Pure virtual function with implementation, If the virtual function call uses an explicit class member access and the object more derived classes, attempting to call a derived class function from a base class that involve calling (non-pure) virtual functions from the constructor of a class,  Interesting, I found an issue with GCC 4.8.2: Base *pBase = (Base*)(void*)new Derived; tried to call my pure virtual functions from my Base class. – Dzenly Mar 27 '19 at 14:59 if call in constructor, the g() base class will be called, because the derived class is not constructed now. – lbsweek yesterday


If PrintStartMessage() was not a pure virtual function but a normal virtual function, the compiler would not complain about it. However you would still have to figure out why the derived version of PrintStartMessage() is not being called.

Since the derived class calls the base class's constructor before its own constructor, the derived class behaves like the base class and therefore calls the base class's function.

Pure virtual (abstract) functions and abstract base classes a special kind of virtual function called a pure virtual function (or abstract function) that has no body at all! 1) The constructor is still accessible from within derived classes, making it  Calling virtual functions from a constructor or destructor is considered dangerous most of the times and must be avoided whenever possible. All the C++ implementations need to call the version of the function defined at the level of the hierarchy in the current constructor and not further. You can call a virtual function in a constructor.


Calling virtual functions from a constructor or destructor is considered of dog(​base) class is called as in above code, Yellowdog(derived) class is not  When a virtual function is called directly or indirectly from a constructor or from a destructor, including during the construction or destruction of the class’s non-static data members, and the object to which the call applies is the object (call it x) under construction or destruction, the function called is the final overrider in the constructor’s or destructor’s class and not one overriding it in a more-derived class.


Sometimes implementation of all function cannot be provided in a base class Such a class is called abstract class. A pure virtual function (or abstract function​) in C++ is a virtual function for 4) An abstract class can have constructors. Performing a virtual method call in a Base class constructor/destructor as a result of creating/deleting a Derived class instance carries a lot of danger depending on the language you are using if the Derived class overrides the specified virtual method and this can result in hard-to-find bugs.


23.5, When my base class's constructor calls a virtual function on its this [23.1] Is it okay for a non-virtual function of the base class to call a virtual function? Yes. pure virtual) but Shape::print() could, if we were guaranteed no derived class  However, since we are invoking bar() from the base class constructor, it tries to call the pure virtual function; it is not possible to invoke a function that is not defined, and hence it results in a runtime exception (technically, it is “undefined behaviour”).