Search code examples
c++inheritanceconstructorsubclassprotected

Will a derived class call a protected constructor in base class before its own constructor?


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()


Solution

  • 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.