Copy constructor C++ -
sorry struggling grasp copy constructors,i know why copy constructor invoked when call object in function value "op.return_value(op)<
class operation{ public: int add(int x,int y){ *total=x+y; return (*total); } operation(){ cout<<"this constructor"<<endl; total=new int; } operation(const operation &op){ cout<<"this copy of start"<<endl; total=new int; *total=*op.total; } ~operation(){ cout<<"this end"; delete total; } int *total; int return_value(operation op){ return *total; } }; class child_operation:operation{ public: int sub(int x,int y){ *total=x-y; return(*total); } }; int main() { operation op; child_operation op1; cout<<op.add(5,6)<<endl<<op1.sub(6,5)<<endl; cout<<op.return_value(op)<<endl; }
basically in ways copy constructor invoked?
it pretty straightforward, , explicitly stated in standard (12.8.1):
a class object can copied in 2 ways, initialization (including function argument passing , function value return) , assignment. conceptually, these 2 operations implemented copy constructor , copy assignment operator.
so, if initializing new object, either explicitly, or implicitly (e.g. passing object function by copy, case, or returning object function), copy constructor called:
myclass = b;//initialization, copy constructor called //or void foo(myclass a){}//a passed value, copy made, , copy constructor called //or myclass foo() { myclass result; return result;//a copy of result returned, , copy constructor called }
on contrary, if making assignment, operator=
called instead, e.g.
myclass x; myclass y; y = x;//assignmanet
Comments
Post a Comment