View Single Post
Re: C++ overriding methods using virtual
Old
  (#7)
botmeister
Ex-Council Member
 
botmeister's Avatar
 
Status: Offline
Posts: 1,090
Join Date: Nov 2003
Location: Canada
Default Re: C++ overriding methods using virtual - 21-06-2004

Maybe I've stayed up too late again, but my understanding of classes is as follows:

The derived class constructor must call the base class constructor before anything is initialized in the derived class. If you have not declared any constructors, the compiler will insert default constructors for you and call them in the proper order. In your case, you have defined a declared constructor, but the same rule applies - the base class constructor always get called before the derived class constructor (the rule makes perfect sense if you think about it).

If you declare a constructor in a derived class, you must call the base class constructor as follows which holds the initilization rule in place:

CSubClass::CSubClass(bool mess_up) : CSuperClass()
{


if ( mess_up )
this->CSuperClass
::CSuperClass();
}

In your case you did not specify the base class constructor, but the compiler will call it for you anyway before CSubClass is called.

When mess_up evaluates to true, your code is attempting to call the base class constructor twice and improperly (which is why you are resorting to using this)!
You cannot prevent a class from executing its constructor, and if you manage to do it, your class will not initialize properly.

One more note about all this, the base class constructor should not make use of variables from the derived class (via a virtual function call) because they won't be initialized until after the base class constructor call is completed. Generally, the compiler will initialize these variables to zero (or null) beforehand anyway, but this is not a rule that can be relied on.



Maker of the (mEAn) Bot.Admin Manager

"In theory, there is no difference between theory and practice. But, in practice, there is." - Jan L.A. van de Snepscheut
  
Reply With Quote