0

Possible Duplicate:
C++ superclass constructor calling rules

How do you delegate work to the superclass' constructor? For instance

class Super {
public:
    int x, y;
    Super() {x = y = 100;}
};
class Sub : public Super {
public:
    float z;
    Sub() {z = 2.5;}
};

How do I get Sub::Sub() to call Super::Super() so that I don't have to set x and y in both constructors?


2 답변


5

Use constructor's member initializer lists:

class Super {
public:
    int x, y;
    Super() : x(100), y(100)  // initialize x and y to 100
    {
       // that was assignment, not initialization
       // x = y = 100;
    }
};
class Sub : public Super {
public:
    float z;
    Sub() : z(2.5) { }
};

You don't need to explicitly call base class' default constructor, it's automatically called before derived class' constructor is ran.

If, on the other hand, you want base class to be constructed with parameters (if such constructor exists), then you need to call it:

class Super {
public:
    int x, y;
    explicit Super(int i) : x(i), y(i)  // initialize x and y to i
    { }
};
class Sub : public Super {
public:
    float z;
    Sub() : Super(100), z(2.5) { }
};

Furthermore, any constructor that can be called without arguments is a default constructor, too. So you can do this:

class Super {
public:
    int x, y;
    explicit Super(int i = 100) : x(i), y(i)
    { }
};
class Sub : public Super {
public:
    float z;
    Sub() : Super(42), z(2.5) { }
};
class AnotherSub : public {
public:
    AnotherSub() { }
    // this constructor could be even left out completely, the compiler generated
    // one will do the right thing
};

And only call it explicitly when you don't want base members to be initialized with default value.

Hope that helps.


1

Call base constructor in member initialize list if you want to, actually Super() constructor is automatically called.

Don't forgot to make Super destructor virtual.

class Super {
public:
    int x, y;
    Super() : x(100),y(100) {}
    virtual ~Super(){}
};

If deletion through a pointer to a Super should be allowed, then Super destructor must be public and virtual.


  • The Super() constructor is automatically called (no need to call it explicitly). Only make the Super class destructor virtual if this is going to be a polymorphic base type (since there are no virtual members this is not necessarily true). - Martin York
  • Note that you don't need to call the base constructor, as it will be implicitly called by the compiler in this case. You only need to explicitly list non-default constructors (to pass the arguments). Loki is also right in that you don't always want to make the destructors polymorphic. - David Rodríguez - dribeas
  • Please, add whitespace before : Super()… - Potatoswatter
  • Please upvote the other one, not this one, next answer captures more and better info than mine. - billz

Linked


Related

Latest