c++ 派生构造函数而不调用基构造函数

icomxhvb  于 2022-12-05  发布在  其他
关注(0)|答案(2)|浏览(554)

我是OOP的新手,我碰巧知道当一个派生类的构造函数(或解构函数)被调用时,一个基类的构造函数(或解构函数)也被调用。但是如果我不想让基类的构造函数/解构函数被调用,我该怎么办呢?

class Base{
    public:
    
    Base(){
        cout<<"Base constructor called\n";
    }
    ~Base(){
        cout<<"Base deconstructor called\n";
    }
};
class Derived: public Base{
    public:
    Derived(){
        cout<<"Derived constructor called\n";
    }
    ~Derived(){
        cout<<"Derived deconstructor called\n";
    }
};
int main()
{
    Derived* obj_a = new Derived;
    delete obj_a;

    return 0;
}

结果是:

Base constructor called
Derived constructor called
Derived deconstructor called
Base deconstructor called
dsf9zpds

dsf9zpds1#

Part of the point of inheritance is that an instance of a derived class is also an instance of the base class. Therefore, when you create a derived object, the base class constructor always runs to establish this as an instance of the base class. Then the derived constructor runs to also establish it as an instance of the derived class.
If you don't want the base class constructor to run, that's fairly directly saying that either the base class constructor is doing things it shouldn't be, or else you don't want this to be an object of the base class after all.
If the problem is with the base class constructor, you obviously fix that.
If the problem is that you don't want your derived object to be an instance of the base class, you have a couple of possible approaches, depending on the precise source of the problem.
One fairly common problem is that the derivation initially seems reasonable, but really isn't. Many people tend to think in terms of similarity. If one thing is 95% like another, with a few things added on, we often think inheritance can be used to represent that reasonably. It can't. We may not be able to use derivation at all, or we may have to create some third class that contains only the 95% that's alike, to act as the base of both of the classes involved. But for things to work well, a derived class must be a strict superset of the base class--it must share 100% of the base class, and add some other "stuff" as well.
Inheritance is misused and abused so often that when I see a question like this, without a description of the specific problem, my first guess is that you're probably misusing inheritance, so this probably isn't just a matter of fixing the base class constructor, it's a matter of needing a different hierarchy, or (more likely) shouldn't really be using inheritance at all.

jecbmhm3

jecbmhm32#

这不是java; base ctor/dtor总是会被调用,因为base的不变式必须被建立,销毁类所需的操作必须被执行。如果你需要以某种方式从后代向base发出信号,表明某些特定的资源不应该被释放,你需要让它成为base状态的一部分;但通常认为这是一个坏模式。

相关问题