InterviewSolution
| 1. |
What are virtual classes? What is the order of invocation of constructors for them? |
|
Answer» You can make a class VIRTUAL if it is a base class that has been PASSED to more than one derived class, as might happen with multiple inheritance. A base class can't be specified more than once in a derived class: class B { ...}; class D : B, B { ... }; // ILLEGALHowever, a base class can be indirectly passed to the derived class more than once: class X : public B { ... } class Y : public B { ... } class Z : public X, public Y { ... } // OKIn this case, each object of class Z will have two sub-objects of class B. If this causes problems, you can add the keyword "virtual" to a base class specifier. For example, class X : virtual public B { ... } class Y : virtual public B { ... } class Z : public X, public Y { ... }B is now a virtual base class, and class Z has only one sub-object of class B. Constructors for Virtual Base Classes: Constructors for virtual base classes are INVOKED before any non-virtual base classes. If the hierarchy CONTAINS multiple virtual base classes, the virtual base class constructors are invoked in the order in which they were declared. Any non-virtual bases are then constructed before the derived class constructor is CALLED. If a virtual class is derived from a non-virtual base, that non-virtual base will be first, so that the virtual base class can be properly constructed. For example, this code class X : public Y, virtual public Z X one; produces this order: Z(); // virtual base class initialization Y(); // non-virtual base class X(); // derived class |
|