Nishikant Nishikant - 2 months ago 6
C++ Question

Why is there a difference in call of constructors when passed by value to a function and pass by value to another constructor?

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.

Answer

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 that how variable should be initialized by member intializer list, like

class MyClass {
    Type variable;  
public:
    MyClass(Type a) : variable(a) {   // variable will be copy initialized
    cout << "inside MyClass constructor "<<endl;
    // variable = a;                  // no need for assignment
    }
};

The default constructor won't be called for this case.