devxlogo

Constructors and virtual functions

Constructors and virtual functions

Question:
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 { public:   virtual void init()      {cout << "This is the base::init() function";}   base()      {      this->init();      }  };class derv : public base  {  public:    void init()      {cout << "This is the derv::init() function";}  };void main()  {derv d1;}
This won’t execute derv::init. Help!

Answer:
You are absolutely correct; calls to virtual functions from a constructorwill never resolve to the derived class (which is not yetconstructed).

Your book is giving you untrue information, because if yourvirtual fn were called before the constructor, almost anythingyou do inside it would cause the program to crash or have undefinedbehavior.

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

See also  Why ChatGPT Is So Important Today
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist