I have learned about three cases about calling the copy constructor
1. A variable is being initialized from an object of the same class
2. A function is called with a value parameter of the class
3. A function is returning a value that is an object of the class
Also textbook says for the above two cases(case2 and 3), to avoid calling copy constructors, use call-by-reference
I have searched for some information but I can't understand exactly.
For example(I made my own code)
class CpClass{
int p;
CpClass(const CpClass &obj){
cout<<"user-defined constructor"<<endl;
p = obj.p;
}
~CpClass(){
cout<<"destructor"<<endl;
}
};
void show1(String &s)
{ cout << "show1 : " << s.p; }
void show2(String s)
{ cout << "show2 : " << s.p; }
int main(){
CpClass c1(10);
CpClass c2(c1);
show1(c2);
show2(c2);
};
I found some information about this.
First, When we pass an argument which is a class object, if the parameter is reference form not value, it does not call the destructor as soon as the function is ended. It calls destructor when the main function is ended
Second, it call constructor when copy argument whether the parameter form is call by value or call by reference(In code, String &s or String s)
Am I correct or not?
As your posted code does not compile I changed it to:
Following lines call a constructor
The first desctructor is called after leaving function
The destructors for
c2
andc1
are called when leavingmain
function (in this order)CpClass &s
is syntactic sugar forCpClass * const s
. That means thats
contains the address of the object and not a copy. Syntactic sugar means that this is a short form and you don't need to dereference.