-1

My derived class should go through the same init procedure as the base class, initializing some vars and setting some states. The following is a simplified example:

class Base
{
    protected:
        int x = 0;

        Base() { x = 1; }
    
};

class Sub : public Base
{
    public:
        void printX()
        {
            printf("%d", x);
        }
};

Will the default constructor of my subclass "Sub" call the protected constructor in the base class? This would mean that x in the subclass would be 1 if printed.

EDIT: added return type for printX()

glades
  • 3,778
  • 1
  • 12
  • 34
  • Downvote as you can easily try it. – Phil1970 Jul 27 '21 at 16:33
  • 1
    Base classes are constructed before derived classes in C++. (Some other OO languages do it the other way around.) – Eljay Jul 27 '21 at 16:35
  • 1
    @Phil1970 you can also easily try what is the output of `int x; std::cout << x;` but you cannot easily know whats wrong with it unless you already know the answer. Trial and error can be very misleading – 463035818_is_not_an_ai Jul 27 '21 at 17:24
  • @463035818_is_not_a_number Observing that 1 is printed is enough to be 90% sure. Then he could add an extra `printf` in the constructor to really be sure. Another reason that show a lack of effort is that the code won't compile because `printX` return type is missing from declaration. Also very easy to check with a debugger. – Phil1970 Jul 27 '21 at 18:18
  • @Phil1970 in general explaining downvotes is discouraged. We could continue to discuss and I wont agree. Nevermind. – 463035818_is_not_an_ai Jul 27 '21 at 18:19
  • @Phil1970 I know I'm using stackexchange wrong. I could test it out and write an extra program. But I keep this as a note to myself and also to others who have the same question. Also I hoped to gain some further insight in how exactly the the constructor calls are ordered which I got with the answer. This is more helpful as I'm still learning C++. – glades Jul 28 '21 at 06:01
  • A side note, don't call virtual function in a constructor. That's [really bad](https://stackoverflow.com/q/962132/4123703) and it's not what you expected. – Louis Go Jul 28 '21 at 06:11

1 Answers1

3

Yes, default constructor is derived class is going to call default constructors of its bases. (It becomes more interesting with virtual inheritance, but there is none in the snippet, so we do not need to go into the horrors of those).

See Implicitly-defined default constructor on https://en.cppreference.com/w/cpp/language/default_constructor for more details:

...That is, it calls the default constructors of the bases and of the non-static members of this class.

SergeyA
  • 61,605
  • 5
  • 78
  • 137