在虚函数中调用构造函数时出现混淆
confusion in constructor calling in virtual function
通过临时对象作为函数参数调用构造函数时的混淆
#include <iostream>
using namespace std;
class Base
{
protected:
int i;
public:
Base() {
cout<<"n Default constructor of Base n";
}
Base(int a)
{
i = a;
cout<<"Base constructor n";
}
void display(){
cout << "nI am Base class object, i = " << i ;
}
~Base(){
cout<<"nDestructor of Basen";
}
};
class Derived : public Base
{
int j;
public:
Derived(int a, int b) : Base(a) {
j = b;
cout<<"Derived constructorn";
}
void display() {
cout << "nI am Derived class object, i = "<< i << ", j = " << j;
}
~Derived(){
cout<<"nDestructor Of Derived n";
}
};
void somefunc (Base obj) //Why there is no call to default constructor of Base class
{
obj.display();
}
int main()
{
Base b(33);
Derived d(45, 54);
somefunc( b) ;
somefunc(d); // Object Slicing, the member j of d is sliced off
return 0;
}
我的问题是,为什么没有调用基类的默认构造函数,当我们在函数(void somefunc(Base obj))中创建基类的临时对象
我的问题是,当我们在函数
中创建基类的临时对象时,为什么没有调用基类的默认构造函数?
在调用somefunc
时,使用复制构造函数构造Base
的实例。该对象不是使用默认构造函数构造的。由于没有定义默认复制构造函数,因此编译器会创建默认复制构造函数。
这不是一个临时对象。参数按值传递给函数,因此将调用复制函数,而不是默认函数。注意,如果没有用户自定义,编译器会提供一个复制构造函数,你可以自己定义它来输出一些调试信息。
Base(const Base& a) : i (a.i)
{
cout<<"Base copy constructor n";
}
它将调用copy construct
函数在函数
相关文章:
- 从具有按值捕获的 lambda 移动构造 std::函数时,移动构造函数调用两次
- 构造函数/函数声明参数列表中的统一初始化
- 在c++中为链接列表创建复制构造函数/函数
- 如何声明模板函数,以便可以在类构造函数/函数中传递
- 在C 中,如何调用构造函数函数
- 在C++中构造模板函数时出现编译错误 C2664 和 C2440
- Rcpp:构造模板函数
- 采用nulltpr_t的构造函数:函数定义不声明参数
- 使用基于模板的构造函数构造std::函数
- 构造函数:函数不接受3个参数
- 就地构造 std::函数目标
- 将字符串构造作为函数参数传递
- C++:从模板化方法构造std::函数
- 构造std::函数的向量时出现编译器错误
- 构造<stl_hashtable>函数参数是否在
- libstdc++和libc++在用lambda构造std::函数时的不同行为
- 编译器构造-带有函数的类的c++sizeof()
- 使用 c++11 构造映射函数
- 调用构造与函数原型混淆
- 在不调用initializer_list构造函数的情况下,将不可复制、不可移动的类型构造为函数形参