Demonstrating that class objects can be assigned to each other using default memberwise copy : Copy Constructor « Class « C++






Demonstrating that class objects can be assigned to each other using default memberwise copy

  
#include <iostream>

using std::cout;
using std::endl;

class Date {
public:
   Date( int = 1, int = 1, int = 1990 ); // default constructor
   void print();
private:
   int month;
   int day;
   int year;
};

// Simple Date constructor with no range checking
Date::Date( int m, int d, int y )
{
   month = m;
   day = d;
   year = y;
}

// Print the Date in the form mm-dd-yyyy
void Date::print() { cout << month << '-' << day << '-' << year; }

int main()
{
   Date date1( 7, 4, 2009 ), date2;  // d2 defaults to 1/1/90

   cout << "date1 = ";
   date1.print();
   cout << "\ndate2 = ";
   date2.print();

   date2 = date1;   // assignment by default memberwise copy
   cout << "\n\nAfter default memberwise copy, date2 = ";
   date2.print();
   cout << endl;

   return 0;
}
  
    
  








Related examples in the same category

1.A copy constructor to allow StringClass objects to be passed to functions.
2.copy constructor: X(X&)