sidell@ux1.cso.uiuc.edu (Jeffrey Sidell) (05/05/91)
Is there a way for the constructor in a derived class to avoid calling the constructor for the class from which it is derived? For example, if I have a class Super which has a constructor of its own, and I derive from it a class Sub, can I make the constructor for Sub completely independent of the constructor for Super? - Jeff Sidell (sidell@ux1.cso.uiuc.edu)
steve@taumet.com (Stephen Clamage) (05/06/91)
sidell@ux1.cso.uiuc.edu (Jeffrey Sidell) writes: >Is there a way for the constructor in a derived class to avoid calling the >constructor for the class from which it is derived? No, by definition of inheritance. The most base class constructor does quite a lot besides the code you supply, such as allocating space if invoked via 'new', and setting up the virtual table. An intermediate class constructor invokes its base class constructors, and modifies as necessary the virtual table, and so on. You don't say what problem you want to solve by omitting base class constructors. If you merely want to omit initialization code under certain circumstances, you can create an empty dummy constructor: class Base { ... public: Base(); // default constructor, does useful work Base(int); // another constructor, does useful work protected: Base(long) { } // protected dummy constructor with empty body }; class Derived : public Base { ... public: Derived(); Derived(int); Derived(<some args>); }; Derived() : Base() { ... ordinary default constructor } Derived(int i1) : Base(i1) { ... another ordinary constructor } Derived(<some args>) : Base(0L) { ... special constructor } Here we have some ordinary constructors, and a special Derived constructor with which you wish to omit the initialization ordinarily performed by the Base constructors. You define a protected Base constructor (so that only derived constructors can access it. This constructor has an empty body, and a unique calling sequence. The Derived constructors which wish to omit the usual base class initialization code specify this dummy constructor with a dummy calling sequence matching that of the dummy Base constructor. The compiler-generated initialization is still performed as it must be, but your usual initialization of the base class is omitted. -- Steve Clamage, TauMetric Corp, steve@taumet.com