Copy constructors : constructor « Class « C++ Tutorial






#include <iostream>
 
 class MyClass
 {
 public:
     MyClass();                          // default constructor
     MyClass (const MyClass &);          // copy constructor
     ~MyClass();                         // destructor
     int GetAge() const { return *itsAge; }
     int GetWeight() const { return *itsWeight; }
     void SetAge(int age) { *itsAge = age; }
 
 private:
     int *itsAge;
     int *itsWeight;
 };
 
 MyClass::MyClass()
 {
     itsAge = new int;
     itsWeight = new int;
     *itsAge = 5;
     *itsWeight = 9;
 }
 
 MyClass::MyClass(const MyClass & rhs)
 {
     itsAge = new int;
     itsWeight = new int;
     *itsAge = rhs.GetAge();
     *itsWeight = rhs.GetWeight();
 }
 
 MyClass::~MyClass()
 {
     delete itsAge;
     itsAge = 0;
     delete itsWeight;
     itsWeight = 0;
 }
 
 int main()
 {
     MyClass myObject;
     std::cout << "myObject's age: " << myObject.GetAge() << "\n";
     std::cout << "Setting myObject to 6...\n";
     myObject.SetAge(6);
     std::cout << "Creating secondObject from myObject\n";
     MyClass secondObject(myObject);
     std::cout << "myObject's age: " << myObject.GetAge() << "\n";
     std::cout << "secondObject' age: " << secondObject.GetAge() << "\n";
     std::cout << "setting myObject to 7...\n";
     myObject.SetAge(7);
     std::cout << "myObject's age: " << myObject.GetAge() << "\n";
     std::cout << "boot's age: " << secondObject.GetAge() << "\n";
     return 0;
 }
myObject's age: 5
Setting myObject to 6...
Creating secondObject from myObject
myObject's age: 6
secondObject' age: 6
setting myObject to 7...
myObject's age: 7
boot's age: 6








9.2.constructor
9.2.1.A parameterized constructor
9.2.2.Use constructor to initialize class fields
9.2.3.Initialize variables and conduct calculation in constructor
9.2.4.Overload the constructor
9.2.5.Copy constructors
9.2.6.Constructor as conversion operator
9.2.7.Virtual copy constructor
9.2.8.overload constructor
9.2.9.Overload constructor two ways: with initializer and without initializer
9.2.10.Call class constructor or not during class array declaration
9.2.11.Call default constructor when allocating an array dynamically
9.2.12.Call constructor from base class to initialize fields inherited from base class
9.2.13.Overload constructor for different data format
9.2.14.Defining and using a default class constructor
9.2.15.Constructor parameter with default value
9.2.16.If a constructor only has one parameter
9.2.17.The default constructor for class X is one that takes no arguments;