user1593881
user1593881

Reputation:

Copy constructor when declaring two objects

Does declaring the following:

MyClass myFirstObject;    
MyClass mySecondObject = myFirstObject;

mean that the copy constructor is used for the second object even if no parameter is passed?

Upvotes: 1

Views: 51

Answers (2)

GingerJack
GingerJack

Reputation: 3134

Yes,A copy constructor is used to initialize an object with a differnt object of same type. Situation where a copy constructor is called

MyClass A;
MyClass B(A);         //Explicit Copy constructor invoked
MyClass C = A;        //Implicit Copy constructor invoked

Upvotes: 2

Don Larynx
Don Larynx

Reputation: 695

An easy way to check is by adding a cout statement in the copy constructor:

MyClass::MyClass(const MyClass&){

std::cout << "I am called!";

/*do stuff*/

}

Upvotes: 0

Related Questions