Copy Constructor Call When Function Returns a Reference to Class Object
Understanding copy constructor call when a function is returning reference to a class object.
Learning Objectives
- Viewing how copy constructor is called when a function returns a reference to an object.
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.
};
C E; //An object E of class type C has been declared. This has been declared globally so that the returned reference can be used by other functions or objects.
C& func() {//This functions is returning a reference to Class type C
return E; //A reference to object E is returned.
}
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.
C c2=func(); //Here another object c2 is being made based on object reference returned by function func()
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 doesn’t return object by reference like this C func() then compilation error would occur.
- If the the object C E; is declared inside the function the returned reference may not be available to other functions and error/warning may be returned by the compiler.
Suggested Filename(s): objreturnedasreference.cpp,obretref.cpp
CSKC| Created: 26-Apr-2019 | Updated: 26-Apr-2019|