Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Home » Tip Bank » C++
Language: C++
Expertise: Beginner
Jul 18, 1997



Building the Right Environment to Support AI, Machine Learning and Deep Learning

Constructors and virtual functions

I have been doing some programming in C++ and recently decided I would try some Windows programming with the Microsoft Foundation Classes. This isn't a question about Windows but about something I saw in the MFC.

Applications are derived from a class called CWinApp but the only function I have to declare in the body of my derived class is an overloaded InitInstance() function. The book I am reading says that when an object of my class is made, the default CWinApp constructor is called. This constructor then calls its virtual function InitInstance(), which in turn calls my overloaded version of the function.

My question is, how does the constructor call the virtual function so that it calls my overloaded version? In all my attempts to duplicate this action, I can only get the constructor of my base class to execute the body of the virtual function defined in the base class. I can't get it to call the overloaded version in my derived class. For example:

class base
   virtual void init()
      {cout << "This is the base::init() function";}

class derv : public base
    void init()
      {cout << "This is the derv::init() function";}

void main()
  {derv d1;}
This won't execute derv::init. Help!

You are absolutely correct; calls to virtual functions from a constructor will never resolve to the derived class (which is not yet constructed).

Your book is giving you untrue information, because if your virtual fn were called before the constructor, almost anything you do inside it would cause the program to crash or have undefined behavior.

Read the source code to find out exactly where the call is made from. It cannot be from the constructor.

DevX Pro
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date