3

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.

Greg Nisbet
  • 6,710
  • 3
  • 25
  • 65
  • I'll say the annoying thing and ask why you want to do this. – Nir Friedman Nov 12 '17 at 03:39
  • @NirFriedman I don't want to and am not going to; I'm wondering whether it's *possible*. Constructors in C++ have some strange behavior compared to other languages I've used (e.g. not being inherited, nullary constructor getting implicitly called, `explicit` ...). I'm trying to get a better feel for the boundaries of the language. – Greg Nisbet Nov 12 '17 at 03:46
  • "*the ordinary way to call a parent class' constructor is in the initialization list*" - it is not just the *ordinary* way, it is the ONLY way. – Remy Lebeau Nov 12 '17 at 04:15
  • @GregoryNisbet The behavior isn't strange, it makes sense if you understand C++. And the answer to your question is no. You can't enter the body without constructing the object. The init answer given below is both not the same thing, and a horrible idea. – Nir Friedman Nov 12 '17 at 19:03

2 Answers2

2

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);
};
mnistic
  • 10,866
  • 2
  • 19
  • 33
0

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.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • Sorry, I should have been more clear. I meant calling the Parent constructor "on" the object being constructed. – Greg Nisbet Nov 12 '17 at 03:19
  • Possibly duplicate of https://stackoverflow.com/questions/308276/can-i-call-a-constructor-from-another-constructor-do-constructor-chaining-in-c ? – JustMe Nov 12 '17 at 03:24