Click to See Complete Forum and Search --> : Constructors and Destructors - calling virtual functions....


JamesSchumacher
September 2nd, 2002, 01:02 PM
I have a question about constructors and destructors calling virtual functions. The code to a simple program I am attaching illustrates my question.

I'd like to know what the standard says about this, because from the information I know - it appears as a VC++ bug. (version 6.0) I say that, because there is a switch in the compiler options for turning on and off the vtable member, and it says only disable this if you are sure constructors and destructors call virtual functions virtually. It does it with the member on or off - failing to call the derived overloaded functions and calling the base class version both times.

Graham
September 2nd, 2002, 01:20 PM
No. You can't call the 'derived' virtual function from a base class ctor or dtor. The simple reason is that, whilst you are in a ctor or dtor the object does not exist. An object's lifetime is from the time the ctor exits to the time it enters the dtor. More specifically, in the base class ctor, the derived ctor has not yet been called, and in the base class dtor, the derived class dtor has already been called. The best you can expect is for it to call the base class version of the virtual function. Which can be problematic if you have this:

class base
{
public:
base() { v1(); }
virtual void v1() = 0;
};

class derived : public base
{
public:
virtual void v1() { /* something */ }
};

Expect fireworks.

JamesSchumacher
September 2nd, 2002, 01:28 PM
I was just confused because MS has that option I stated above that says "constructors and destructors to call virtual functions virtually." - Which is saying to me - that constructors and destructors can call virtual functions. Then again, I know MS is hardly the people to look at for any standard issue.

Although, with your code example I thought you had to 'virtual' inherit from a base with a pure virtual function? I've never had to use a base with pure virtual functions, so I have to go on what I know from reading. Okay, I tried it - no need for 'virtual' inheritance - I was confusing it with inheriting from two classes that inherit from the same base class. 'virtual' inheritance is for getting one copy of an ambiguity of deriving from two or more classes with a common base. Like having a car class as a base for all cars, a ford and chevy class both derived from car, and creating a hybrid derived from both ford and chevy - a need for virtual inheritance right there.

Zeeshan
September 2nd, 2002, 11:59 PM
I have written one complete artical on this which might be helpful to you. Take a look at

http://www.codeguru.com/atl/ATL_UndertheHood_2.html

Hope it helps.