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.

Share the Post:
Heading photo, Metadata.

What is Metadata?

What is metadata? Well, It’s an odd concept to wrap your head around. Metadata is essentially the secondary layer of data that tracks details about the “regular” data. The regular

XDR solutions

The Benefits of Using XDR Solutions

Cybercriminals constantly adapt their strategies, developing newer, more powerful, and intelligent ways to attack your network. Since security professionals must innovate as well, more conventional endpoint detection solutions have evolved

AI is revolutionizing fraud detection

How AI is Revolutionizing Fraud Detection

Artificial intelligence – commonly known as AI – means a form of technology with multiple uses. As a result, it has become extremely valuable to a number of businesses across

AI innovation

Companies Leading AI Innovation in 2023

Artificial intelligence (AI) has been transforming industries and revolutionizing business operations. AI’s potential to enhance efficiency and productivity has become crucial to many businesses. As we move into 2023, several