简体   繁体   中英

Is the base class constructor excuted if the derived class does not have a constructor?

This a basic concept that I'm not sure of, and I need to have a clearer understanding. My question is, does the base class constructor get executed even if the derived class does not have a constructor? Or is the base constructor call not related to the derived constructor? Thank you for explaining!

A constructor is always executed for every base class. This includes compiler-generated default constructors. If it's not possible to call a base class constructor, you will always get an error message.

Yes, by default, the default constructor of the base class is executed.

Note that this applies for all derived class constructors - they all call the default constructor unless you specify a different one. This means that a copy constructor in a derived class (user-defined or compiler generated) will, by default, call the default base class constructor.

Generally speaking, the base class's constructor will get called before the derived class's constructor.

Here's a good SO thread explaining it: Does a base class's constructor and destructor get called with the derived ones?

是的,即使您的派生类没有构造函数,也可以执行基类构造函数

Yes. If not defined the compiler conjures up one for you and uses that

Even if you do not define a constructor by yourselves, default constructor will be added by the compiler.

By default, derived class constructor will call the default constructor of the base class before the execution of the body of the derived class constructor.

If you want, you can call the constructor of the base class in the initialization list of the constructor of the derived class.

Here is an example.

class Base
{
public:
    Base(int nValue)
    {
        //body of the constructor
    }
};

class Derived: public Base
{
public:

    Derived(int mnValue) :Base(mnValue)
    {
        //body of the constructor
    }
};

In the above example, derived class call the constructor of the Base class explicitly in the initialization list of the constructor of the derived class.

For more information, please refer to

http://www.learncpp.com/cpp-tutorial/113-order-of-construction-of-derived-classes/

http://www.learncpp.com/cpp-tutorial/114-constructors-and-initialization-of-derived-classes/

Whenever you create an object its constructor runs. Whenever you destroy an object its destructor runs. Regardless of whether the object is a member, a base, or anything else. That's fundamental to object-oriented programming.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM