Showing posts with label Copy Constructor. Show all posts
Showing posts with label Copy Constructor. Show all posts

Days, Months, Years Program to show Copy Constructor in C++


#include<iostream.h>
#include<conio.h>

class PERIOD
{
    int days, months,years;
  public:
    void show();
    PERIOD(int d,int m,int y);
    PERIOD(const PERIOD &);
};

void PERIOD::show()
{
      cout<<days<<months<<years<<endl;
}

PERIOD::PERIOD(int d,int m,int y)
{
      days=d;months=m;years=y;
}

PERIOD::PERIOD(const PERIOD &tmp)
{
      cout<<"Copied"<<"\n";
      days=tmp.days;months=tmp.months;years=tmp.years;
}

int main ()
{
clrscr();
   PERIOD p1(10,6,100);
   p1.show();
   PERIOD p2(p1);
   p2.show();
  getch();
  return 0;
}

Copy Constructor # 2


/* This program creates a "safe" array class. Since space
for the array is allocated using new, a copy constructor
is provided to allocate memory when one array object is
used to initialize another.
*/
#include <iostream.h>
#include <conio.h>
//using namespace std;
class array
{
      int *p;
      int size;
      public:
      array(int sz)
      {
            p = new int[sz];
            size = sz;
      }

      ~array()
      {
            delete [] p;
      }
// copy constructor

      array(const array &a);

      void put(int i, int j)
      {
            if(i>=0 && i<size) p[i] = j;
      }

      int get(int i)
      {
            return p[i];
      }
};
// Copy Constructor

array::array(const array &a)
{
      int i;
      p = new int[a.size];

      for(i=0; i<a.size; i++) p[i] = a.p[i];
}

int main()
{
      clrscr();
      array num(10);
      int i;
      for(i=0; i<10; i++) num.put(i, i);
      for(i=9; i>=0; i--) cout << num.get(i);
      cout << "\n";
      // create another array and initialize with num
      array x(num); // invokes copy constructor
      for(i=0; i<10; i++) cout << x.get(i);
      getch();
      return 0;

}
Custom Search