Ok, im reading Sams Teach yourself C++ in 21 days, overall i like it. But there is one thing i am highly confused by.
At the moment i am reading about passing by refrences, passing objects atm. And in the code example i am about to copy to you i do not understand what the copy constructor is for. That and the refrence opterator behind the class name (eg below)
So can someone help? Thanks!Code:public: SimpleCat(); // original constructor SimpleCat(SimpleCat&); // copy constructor ~SimpleCat(); // obviously deconstructor
so if you can, please expain to me the reason for the copy constructor existing, and what it is lol. Thanks! (that and the refrence operator behind SimpleCat (ie "(SimpleCat&)") thanks!Code:1: //Listing 9.12 2: // Passing references to objects 3: 4: #include <iostream.h> 5: 6: class SimpleCat 7: { 8: public: 9: SimpleCat(); 10: SimpleCat(SimpleCat&); 11: ~SimpleCat(); 12: 13: int GetAge() const { return itsAge; } 14: void SetAge(int age) { itsAge = age; } 15: 16: private: 17: int itsAge; 18: }; 19: 20: SimpleCat::SimpleCat() 21: { 22: cout << "Simple Cat Constructor...\n"; 23: itsAge = 1; 24: } 25: 26: SimpleCat::SimpleCat(SimpleCat&) 27: { 28: cout << "Simple Cat Copy Constructor...\n"; 29: } 30: 31: SimpleCat::~SimpleCat() 32: { 33: cout << "Simple Cat Destructor...\n"; 34: } 35: 36: const SimpleCat & FunctionTwo (const SimpleCat & theCat); 37: 38: int main() 39: { 40: cout << "Making a cat...\n"; 41: SimpleCat Frisky; 42: cout << "Frisky is " << Frisky.GetAge() << " years old\n"; 43: int age = 5; 44: Frisky.SetAge(age); 45: cout << "Frisky is " << Frisky.GetAge() << " years old\n"; 46: cout << "Calling FunctionTwo...\n"; 47: FunctionTwo(Frisky); 48: cout << "Frisky is " << Frisky.GetAge() << " years old\n"; 49: return 0; 50: } 51: 52: // functionTwo, passes a ref to a const object 53: const SimpleCat & FunctionTwo (const SimpleCat & theCat) 54: { 55: cout << "Function Two. Returning...\n"; 56: cout << "Frisky is now " << theCat.GetAge(); 57: cout << " years old \n"; 58: // theCat.SetAge(8); const! 59: return theCat; 60: } Output: Making a cat... Simple Cat constructor... Frisky is 1 years old Frisky is 5 years old Calling FunctionTwo... FunctionTwo. Returning... Frisky is now 5 years old Frisky is 5 years old Simple Cat Destructor...



LinkBack URL
About LinkBacks


