通过临时对象作为函数中的参数调用构造函数时的混淆
#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 Base\n";
}
};
class Derived : public Base
{
int j;
public:
Derived(int a, int b) : Base(a) {
j = b;
cout<<"Derived constructor\n";
}
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) )