当前位置:网站首页>When a subclass calls the constructor of its parent class
When a subclass calls the constructor of its parent class
2022-07-27 06:43:00 【Mr FF】
1 When creating a subclass object , The constructor of the parent class is called before the constructor of the child class .( Deconstruction time , The destructor of the subclass is called first )
2 If the parent class has multiple constructors , If... Is not specified in the subclass constructor , Then call the default constructor or parameterless constructor of the parent class . otherwise , Call according to the parent constructor type specified in the subclass constructor . Please look at the following example
#include <iostream>
#include <string>
using namespace std;
class Weapon {
public:
Weapon()
{
cout << "Weapon constructor" << endl;
}
Weapon(int value, string name) : m_value(value), m_name(name)
{
cout << "Weapon constructor"
<< ", value is: " << m_value
<< ", name is: " << m_name
<< endl;
}
virtual ~Weapon()
{
cout << "Weapon destructor" << endl;
}
private:
int m_value;
string m_name;
};
class Sold : public Weapon {
public:
Sold(float damage) : m_damage(damage) , Weapon(10, "killer") {
cout << "Sold constructor"
<< ", damage is: "
<< m_damage
<< endl;
}
virtual ~Sold()
{
cout << "Sold destructor" << endl;
}
private:
float m_damage;
};
int main()
{
Sold sold(27.8);
return 0;
}Running results :
Weapon constructor, value is: 10, name is: killer
Sold constructor, damage is: 27.8
Sold destructor
Weapon destructor边栏推荐
猜你喜欢
随机推荐
Decorator functions and the use of class decorators
Concept and principle of DHCP
Rsync remote synchronization
3D打印品牌的康复骨科支具有何特别之处?
PXE efficient batch network installation
ESXI虚拟机启动,模块“MonitorLoop”打开电源失败
备忘录 @RestControllerAdvice与异常拦截类示例
Remote access and control
FTP服务简介与配置
Summary of frequently asked questions in the interview [summarized after painstaking work all night]
shell--变量的运算
Network troubleshooting: Ping and tracert commands
DHCP principle and configuration
Shell script backup MySQL database
iptables防火墙
DHCP的概念和原理
NFS简介和配置
Database commands
Publish a building segmentation database with a resolution of 0.22m
PXE高效批量网络装机









