2

Just a quick yes/no question. Calling the parent constructor via

child(someargs) : parent(somelessargs){...} 

calls the parent constructor in the beginning, before all code in {...}, right? Is there a way to call it elsewhere?

This post: C++ Inherit class with sending modified parameters to parent's constructor makes it seem unlikely (although I haven't read through all of the answer, because it doesn't seem to answer my question).

Community
  • 1
  • 1
dasWesen
  • 579
  • 2
  • 11
  • 28
  • 5
    No, the parent class constructor is always called ***before*** the child class constructor. – πάντα ῥεῖ Jul 20 '16 at 09:02
  • That doesn't make sense. In order to construct child object, parent object must, already, exist. – Algirdas Preidžius Jul 20 '16 at 09:04
  • It is like with shoes and socks. You first put on your socks, then the shoes. Later you first take of the shoes then the socks, but you cant take off your shoes while taking of the socks... – 463035818_is_not_an_ai Jul 20 '16 at 09:04
  • 2
    There is this workaround: http://stackoverflow.com/questions/5894940/calling-the-constructor-of-the-base-class-after-some-other-instructions-in-c – pinturic Jul 20 '16 at 09:06
  • Thanks @Bo Persson, and also pinturic, I completely agree, this is a duplicate. Hadn't found the other question (maybe because I searched for "parent class" instead of "base class". That other posts' first answer seems to be a solution! – dasWesen Jul 21 '16 at 08:32

1 Answers1

3

No. That doesn't make sense because after you enter the {...} the default constructor already worked and the parent object built.

Ohad Eytan
  • 8,114
  • 1
  • 22
  • 31
  • The problem was that I wanted to have a sanity check of the parameter that is passed to the base constructor. That parameter can have an additional field, but this field will only be there in the case of the derived class. The code right now will not work if that parameter is, say, "true", so I wanted to check and re-set it if necessary. But maybe you are right anyway: my base constructor called a constructor of another base class with virtual functions, and it seems that is impossible anyway. So my code was flawed from the start - although I'm still not convinced that you'd never need this. – dasWesen Jul 21 '16 at 08:48
  • Templates might be the right way here. Wow such a long comment o.o – dasWesen Jul 21 '16 at 08:49
  • @dasWesen you can make the sanity check with a function and use the workaround suggested [here](http://stackoverflow.com/a/5898066/2069380) – Ohad Eytan Jul 21 '16 at 08:58
  • Yes, that should work (that's what I meant with my other comment. It's really a duplicate.) – dasWesen Jul 21 '16 at 09:00