Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
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

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 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.

 

 

Sitemap