We’ve seen two ways to initialize objects. A no-argument constructor can initialize data members to constant values, and a multi argument constructor can initialize data members to values passed as arguments. Let’s mention another way to initialize an object: you can initialize it with another object of the same type. Surprisingly, you don’t need to create a special constructor for this; one is already built into all classes. It’s called the default copy constructor. It’s a one argument constructor whose argument is an object of the same class as the constructor. The ECOPYCON program shows how this constructor is used.
// ecopycon.cpp // initialize objects using default copy constructor #include <iostream> using namespace std; //////////////////////////////////////////////////////////////// class Distance //English Distance class { private: int feet; float inches; public: //constructor (no args) Distance() : feet(0), inches(0.0) { } //Note: no one-arg constructor //constructor (two args) Distance(int ft, float in) : feet(ft), inches(in) { } void getdist() //get length from user { cout << “\nEnter feet: “; cin >> feet; cout << “Enter inches: “; cin >> inches; } void showdist() //display distance { cout << feet << “\’-” << inches << ‘\”’; } }; //////////////////////////////////////////////////////////////// int main() { Distance dist1(11, 6.25); //two-arg constructor Distance dist2(dist1); //one-arg constructor Distance dist3 = dist1; //also one-arg constructor //display all lengths cout << “\ndist1 = “; dist1.showdist(); cout << “\ndist2 = “; dist2.showdist(); cout << “\ndist3 = “; dist3.showdist(); cout << endl; return 0; }
We initialize dist1 to the value of 11’-6.25” using the two-argument constructor. Then we define two more objects of type Distance, dist2 and dist3, initializing both to the value of dist1. You might think this would require us to define a one argument constructor, but initializing an object with another object of the same type is a special case. These definitions both use the default copy constructor. The object dist2 is initialized in the statement Distance dist2(dist1);
This causes the default copy constructor for the Distance class to perform a member-by-member copy of dist1 into dist2. Surprisingly, a different format has exactly the same effect, causing dist1 to be copied member-by-member into dist3:
Distance dist3 = dist1;
Although this looks like an assignment statement, it is not. Both formats invoke the default copy constructor, and can be used interchangeably. Here’s the output from the program:
dist1 = 11’-6.25”
dist2 = 11’-6.25”
dist3 = 11’-6.25”
This shows that the dist2 and dist3 objects have been initialized to the same value as dist1. “Virtual Functions,” we discuss how to create your own custom copy constructor by overloading the default.
Read More Topics |
C++ Objects as Physical Objects |
Inline function in C++ |
Relationship Between C and C++ |
Virtual Function in C++ |