Categories: MSDN / DotNet / Java / Scripts / Linux / PHP Ask - La ask - La Answer

Virtual Function mechanism in c++

I have some pieces of texts from articles on virtual functions...

Inside an ordinary member function you can imagine what will happen if you call a virtual function the virtual call is resolved at runtime because the object cannot know whether it belongs to the class the member function is in, or some class derived from it.

also..

Once the VPTR is initialized to the proper VTABLE, the object in effect "knows" what type it is.

also..

When a constructor is called, one of the first things it does is initialize its VPTR. However, it can only know that it is of the current type the type the constructor was written for. The constructor code is completely ignorant of whether or not the object is in the base of another class.

in all these texts, i dnt understand what the author means by "the object knows"??, what and how it can know? what does the word knows refer to?

also, so is it true that when we make an object and then the constructors are called from most base to current class in inheritance chain, then vptr also gets initialized in each constructor to vtable corresponding to that class in the inheritance chain till constructor of the current class is called finally in the constructor calls chain and it initializes the final state of vptr to vtable of the current class?? :confused:
[1365 byte] By [premartha] at [2007-11-11 7:06:17]
# 1 Re: Virtual Function mechanism in c++
What is meant by 'know' is 'the compiler can determine that the object is of this type or has these members or whatnot'. Know implies a living being -- using it in this way is one of those messed up "common usage" things found in every language.
jonnin at 2007-11-11 21:02:39 >
# 2 Re: Virtual Function mechanism in c++
"knows" refers to the type information that the object being initialized has access to. If you use some for of type detection inside the constructor, say typeid(*this), you will get the this type. Another way to determine what the object knows about its owen type is calling a virtual function and examining which function is called: the base class's or the derived's.

When there is an inheritance chain, each constructor performs its own initialization, because the same constructor is used to initialize an object of thus type, regardless of whether the object being initialized is a derived object or a base class object. So by the time the base class ctor has finished executing but the derived ctor hasn't yet started, the object has access to the VTABLE of the base class, not the derived's. Only after the most derived class's constructor has finished executing (successfully, that is), is the object considered fully constructed and its liftime begins.
Danny at 2007-11-11 21:03:39 >