"self" constructor

Martin v. Loewis martin@loewis.home.cs.tu-berlin.de
Thu Mar 23 00:59:00 GMT 2000


> I guest "super()" isn't in c++ is because c++ has
> multi-inheritance. But why not "this()"?

Instead of super, you'll have to use the name of the base class, in
the colon member initializer list. However, delegation of one
constructor to another is not supported in C++. Consider

class test:Base {
private:
    int i;
    int j;
public:
    test(int ii):Base("Hello"), i(ii) {};
    test(int ii, int jj):Base(), test(ii), j(jj) {};
}

Base classes are initialized before derived classes, and the
constructor seems to say to use the parameter-less constructor for
initializing base. Then you jump to the other ctor, and see a
different base initialization???

Anyway, it is not supported - the typical solution is to make a
private method to hold the shared code, and to invoke that from each
ctor.

You may find that you can remove a number of ctors by providing
default arguments:

class test {
private:
    int i;
    int j;
public:
    test(int ii, int jj=0):i(ii), j(jj) {};
}

Also note that member variables are *not* normally zero-initialized in
C++.

Regards,
Martin



More information about the Gcc mailing list