Reputation: 95
I was trying the following program :
#include <iostream>
using namespace std;
class Type{
int i;
public:
Type() {cout << "type constructor "<<endl;}
Type (const Type &) { cout << "type copy constructor called" << endl;}
};
class MyClass {
Type variable;
public:
MyClass(Type a) {
cout << "inside MyClass constructor "<<endl;
variable = a;
}
};
void fun (Type){
return;
}
int main (){
Type t;
cout <<"t created"<<endl;
MyClass tmp = MyClass(t);
cout<<"calling fun"<<endl;
fun(t);
}
The output of this is :
type constructor
t created
type copy constructor called
type constructor
inside MyClass constructor
calling fun
type copy constructor called
I am wondering why default constructor is called when I pass it to MyClass
constructor and why copy constructor is called when I pass it to fun()
?
BTW same happens when I use initializer list.
Upvotes: 2
Views: 57
Reputation: 172884
I am wondering why default constructor is called when I pass it to MyClass constructor
It has nothing to do with passing argument here. As a member variable, variable
will be default constructed at first.
class MyClass {
Type variable;
public:
MyClass(Type a) { // variable will be default constructed at first, since it's not initialized via member initializer list
cout << "inside MyClass constructor "<<endl;
variable = a; // then variable is assgined via assignment operator
}
};
You can specify how variable
would be initialized by member intializer list, like
class MyClass {
Type variable;
public:
MyClass(Type a) : variable(a) { // variable will be direct initialized via copy constructor
cout << "inside MyClass constructor "<<endl;
// variable = a; // no need for assignment
}
};
The default constructor won't be called for this case.
Upvotes: 2
Reputation: 50540
Copy constructor is invoked for both the parameters (the one for MyClass
constructor and the one for fun
) and the logs you posted report that.
In fact, you have two times the following line:
type copy constructor called
Default constructor is invoked for data member variable
, for it is not explicitly initialized.
The same happens if you use an initializer list like this:
MyClass(Type a): variable{} {
//...
}
Actually, variable
is default initialized if you don't have any initializer list, so there is no reason to expect a different log.
Upvotes: 0