Greg Nisbet
Greg Nisbet

Reputation: 6994

C++ explicitly call parent constructor outside initialization list

So, the ordinary way to call a parent class' constructor is in the initialization list:

e.g.

#include <cstdio>

struct Parent {
  explicit Parent(int a) {
    printf("Parent -- int\n");
  }
};

struct Child : public Parent {
  explicit Child(int a) : Parent(1) {
    printf("Child -- int\n");
  }
};

int main(int argc, char **argv) {
  Child c = Child(10);
};

prints Parent -- int then Child -- int.

(Somewhat) disregarding whether it's a good idea or not, I'm wondering whether it's possible to call the parent constructor explicitly in the body of the constructor (on the object being constructed), outside the initialization list.

Upvotes: 3

Views: 1300

Answers (2)

mnistic
mnistic

Reputation: 11020

No, not in the way you want, so it constructs the parent part of the object.

The common way to deal with a situation like this is to have an "init" or "construct" method that you then can invoke from the child constructor:

struct Parent {
    explicit Parent(int a) {
        Construct(a);
    }
protected:
    void Construct(int a) { printf("Parent -- int\n"); }
    Parent() {}
};

struct Child : public Parent {
    explicit Child(int a) {
        Parent::Construct(a);
        printf("Child -- int\n");
    }
};

int main(int argc, char **argv) {
    Child c = Child(10);
};

Upvotes: 2

Some programmer dude
Some programmer dude

Reputation: 409176

Well you can but it will not do the same thing.

Doing e.g.

explicit Child(int) {
    Parent(1);
}

will not initialize the Parent part of the object. Instead it will create a new temporary object of type Parent, and then that temporary object will immediately be destructed.

Upvotes: 0

Related Questions