如何在C ++中调用基类构造函数 [英] How are base class constructors called in c++

查看:70
本文介绍了如何在C ++中调用基类构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是C ++的新手我有2个关于如何调用基本构造函数的查询.

I am new to c++ I have 2 queries regarding how a base constructor is called.

1.)可以说我的代码看起来像这样.

1.) Lets say my code looks somewhat like this.

#include<iostream>
using namespace std;

class Base  {
public:
    Base()    { cout<<"Constructor: Base"<<endl; }
    virtual ~Base()   { cout<<"Destructor : Base"<<endl; }
};

class Derived: public Base {
public:
    Derived()   { cout<<"Constructor: Derived"<<endl; }
    ~Derived()  { cout<<"Destructor : Derived"<<endl; }
};

int main()  {
    Base *Var = new Derived();
    delete Var;
    return 0;
}

有人告诉我,必须在初始化列表定义派生构造函数之前显式调用基本构造函数.但是这里没有任何对基本构造函数的调用,代码可以按预期工作.

I was told that a base constructor has to be called explicitly before defining the derived constructor by initialization list. But here without any call to the base constructor, the code is working as expected.

**The output for the above problem is**

Constructor: Base
Constructor: Derived
Destructor : Derived
Destructor : Base

2.)现在假设基类构造函数接受参数化的参数,但是派生的构造函数为空.在主函数中,我声明了一个派生对象,而该构造函数没有任何参数.会发生什么?有什么办法可以单独为该对象的基本构造函数传递参数?

2.) Now suppose the base class constructor takes parametrized arguments, but the derived constructor is empty. In the main function, I declare a derived object without any argument to the constructor. what will happen? Any way to separately pass the base constructor of that object an argument?

谢谢.

推荐答案

如果要从 Derived 调用的 Base 构造函数不是默认值,只需使用初始化列表,例如:

If the Base constructor you want to call from Derived isn't the default, simply use an initialisation list, something like:

Derived::Derived() : Base(args) {
    // ...
}

这篇关于如何在C ++中调用基类构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆