Constructor and Destructor Inheritance

♀尐吖头ヾ 提交于 2020-02-01 04:05:08

问题


I believe Constructors and Destructors in base class cannot be inherited by derived classes of the base class. Is my understanding correct.


回答1:


Your understanding is correct. For example, if you have

class Base
{
  Base(int i) {}
};

class Derived: public Base {};

Derived d(3);

This will not compile because the Base constructor is not inherited. Note that default and copy constructor are created by the compiler if possible, and call the corresponding constructor of base classes, therefore for those constructors it looks as if those were inherited.




回答2:


I think this is what you are looking for? You can call the superclass constructor by adding the following to your class constructor

SubClass(int foo, int bar)
    : SuperClass(foo)

A full example can be found here What are the rules for calling the superclass constructor?




回答3:


On the contrary, each constructor of a derived class calls a constructor of the base [super-] class. Each destructor of a derived class is called just before the destructor of the base [super-] class.

Inheritance concerns classes, not functions or constructors.




回答4:


No, they are inherited. Destructors, for one, are always inherited and called in the order reverse to the creation. For example if we have classes foo, bar and xyzzy:

class foo { ... };
class bar : public foo { ... };
class xyzzy : public bar { ... };

Then if you destoy an object of class xyzzy, destructors will be called in the following order: ~xyzzy(), ~bar() and finally ~foo().

Constructors are also always inherited, but they cannot be called directly. You have to use them in the constructor initialization list or the default constructor will be called (default constructor is the one that takes no arguments).For example, say we have following classes:

class foo {
public:
    foo();
    foo (int _value);
}

class bar : public foo {
    int m_value;

public:
    bar (int _value);
}

bar::bar (int _value)
{
    m_value = _value;
}

In this case, when you create an object of class bar, a constructor for foo is invoked, but it's the default constructor (foo()). Constructor that takes an argument foo (int _value) is never called. But if we changed definition of the bar (int _value) constructor to this:

bar::bar (int _value)
    : foo (256 - _value), m_value (_value)
{
}

Then instead of a default constructor, foo (int _value) will be called.




回答5:


As this question explains, constructors are not inherited. The same applies to destructors.



来源:https://stackoverflow.com/questions/8103805/constructor-and-destructor-inheritance

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!