Copy Constructor Call When Passed as Value to A Function
Understanding copy constructor call when class object is passed as value to a function.
Learning Objectives
- Viewing how copy constructor is called when object are passed by value to a function.
Source Code
|
Run Output
Code Understanding
int x,y; //Global variables declared so that this demo allows them to use from different functions.
class C { //Class C declared
public:
C(){ x=10;} //Default Constructor sets x as 10.
C(C& D) { x=20;} //Copy Constructor sets x as 20.
};
void func(C E){ } //Function where object E of type C is passed as value. Function doesn’t perform any job. It will just depict use of copy constructor as object has been passed as value here.
int main(){
C c1; //c1 is an object based on C, so just default constructor would be called.
cout<<x<<endl; //This prints 10 as default constructor has set x as 10.
func(c1); //Actual function call with object of C which is c1. Now copy constructor would be called.
cout<<x<<endl; //This would print 20 as copy constructor has now been called.
return 0;
}
Notes
- Copying copy constructor can be called in many other situations like
– Creating copy of an object.
– When Object is called by value to a function.
– When Object is returned from a function.
– When temporary objects are created.
Common Errors
- If function calls object by reference like this void func(C& E){ } then only normal constructor would run and value 10 10 would be printed.
Suggested Filename(s): objpassedasvalue.cpp,objpval.cpp
CSKC| Created: 26-Apr-2019 | Updated: 26-Apr-2019|