CONSTRUCTORS AND DESTRUCTORS(Конструкторы и деструкторы)

Constructors and destructors(Конструкторы и деструкторы)
  
Program အား process လုပ္ေနခ်ိန္တြင္ class ၏ data element ဆီသို႕ values မ်ား assign(присвоить)  ၿပဳလုပ္နိဳင္သည္။ထိုသို႕ၿပဳလုပ္ရန္အတြက္ class ၏ special function တစ္ခုၿဖစ္ေသာ constructor function အားအသံုးၿပဳနိဳင္သည္။
constructor ဆိုသည္မွာ object အားတည္ေဆာက္လိုက္ေသာအခ်ိန္တြင္ အလိုအေလ်ာက္ ၿဖစ္ေပၚလာေသာ class ၏ member function တစ္ခုၿဖစ္သည္။ထို႕ေၾကာင့္ object တစ္ခုအား အသံုးၿပဳလိုက္ေသာ အခ်ိန္တြင္ constructor သည္အလိုအေလ်ာက္ အလုပ္လုပ္ေနမည္ၿဖစ္သည္။ထိုကဲ့သို႕ အလိုအေလ်ာက္ၿပဳလုပ္ေသာ variable declaration statement အား C++ ပရိုဂမ္တြင္ “statement of action”(оператором действия) ဟုေခၚဆိုသည္။
global object constructor မ်ားသည္ ပရိုဂမ္မ်ားစတင္ execution ၿပဳလုပ္ခ်ိန္တြင္ active ၿဖစ္သည္ဟုေၿပာဆိုနိဳင္သည္။local object constructor မ်ားသည္ operator မ်ား variable declare ၿပဳလုပ္တိုင္း active ၿဖစ္မည္ၿဖစ္သည္။
constructor အားအသံုးၿပဳရေသာ အဓိကအေၾကာင္းအရင္းမွာ class ၏ data member မ်ားသည္ class function မ်ား၏ definitation ထဲရွိ intital value အၿဖစ္သို႕ တိုက္ရိုက္မေရာက္ရွိနိဳင္ ေသာေၾကာင့္ၿဖစ္သည္။


constructor ဆိုသည္မွာ function-element(функция-элемент) တစ္ခုၿဖစ္ၿပီး ၎ name သည္ class name နွင့္ တူညီရမည္ၿဖစ္သည္။ထို constructor သည္  ထို class ၏ object တည္ေဆာက္တိုင္း active ၿဖစ္မည္ၿဖစ္သည္။အကယ္၍ programmer သည္ constructor အား define မၿပဳလုပ္ပါက complier သည္အလိုအေလွ်ာက္ parameter မပါေသာ empty body ရွိေသာ function အားအလိုအေလွ်ာက္ ေၾကၿငာသြားမည္ၿဖစ္သည္။
Constructor တြင္ေအာက္ေဖာ္ၿပပါ properties(ဂုဏ္သတၱိ) မ်ားရွိသည္။

  •       for the constructor does not specify a return type   // return type မလိုေပ။
  •       constructor can not return a value                       // မည္သည့္ value မွ return
                                                                                     ၿပန္လိမ့္မည္မဟုတ္ေပ။
  •       constructor is not inherited,                              // inherit ၿပဳလုပ္လိမ့္မည္မဟုတ္ေပ။
  •       constructor cannot be declared as const, volatile, virtual, static.
                                                               //    const,volatile,static အၿဖစ္ေၾကၿငာ၍မရေပ။
Constructor သည္ class ၏ object ၏ အမ်ိဳးမ်ိဳးေသာ initial value မ်ားအား ေထာက္ပံ့ရန္အတြက္ overload ၿပဳလုပ္နိဳင္သည္။
Constructor ၏ inverse constructor(обратной конструктору) သည္ destructor ၿဖစ္ၿပီး object တစ္ခုခုအား delete ၿပဳလုပ္ရန္ အတြက္ call ေခၚေသာအခါ အသံုးၿပဳသည္။ထိုသို႕ object တစ္ခုအား delete ၿပဳလုပ္ေနခ်ိန္တြင္ ထို delete ၿပဳလုပ္လိုက္ေသာ object ၏ memory ေနရာသည္ release(освобождение) ၿဖစ္သြားၿခင္းသကဲ့သို႕ေသာ action တစ္ခုခု ၿဖစ္လိမ့္မည္ၿဖစ္သည္။
class ထဲတြင္ destructor အားအသံုးၿပဳ၇န္အတြက္ ၎နွင့္သက္ဆိုင္ေသာ constructor class name ၏နာမည္နွင့္အတူ သေကၤတ ~ (tilde) အားအစတြင္ထည့္ေပးရမည္ၿဖစ္သည္။ အကယ္၍ destructor အားတိက်စြာမေၾကၿငာခဲ့လွ်င္ constructor သကဲ့သို႔ပင္ complier သည္ empty function တစ္ခုအား တည္ေဆာက္ေပးသြားလိမ့္မည္ၿဖစ္သည္။
Deconstructor တြင္ေအာက္ေဖာ္ၿပပါ ဂုဏ္သတၱိမ်ားပိုင္ဆိုင္သည္။

  •        destructor takes no arguments,
  •        destructor may not return a value
  •        destructor is not inherited, except in the case of virtual destructor
  •        destructor can be declared as const, volatile, static,
  •        destructor can be declared as virtual.


Object တစ္ခုအား ပယ္ဖ်က္လိုေသာအခါ class ၏ destructor အားအသံုးၿပဳေလ့၇ွိသည္။ သို႕ေသာ္ object သည္ ၎ကိုယ္တိုင္ ပယ္ဖ်က္လိုက္ၿခင္းမဟုတ္ပဲ system သည္ ၎ object တည္ရွိေနေသာ memory ေနရာမွ ေနရာရရန္ စတင္ယူေဆာင္(ငွားရန္း) အသံုးၿပဳၿခင္းသကဲ့သို႕ေသာ action တစ္ခု ထည့္ေပါင္းၿခင္းၿဖစ္သည္။
Deconstructor မ်ားတြင္ parameter မတည္ရွိေသာေၾကာင့္ class မ်ားတြင္ deconstructor တစ္ခုသာ တည္ရွိနိဳင္ၿပီး overload deconstructor(overload deconstructor) မ်ားအား အသံုးၿပဳနိဳင္လိမ့္မည္ မဟုတ္ေပ။
Class တြင္ object မ်ားတည္ေဆာက္ေသာအခါ မေမွ်ာ္လင့္ေသာ function_element မ်ားလည္း ၿဖစ္ေပၚလာေစတက္သည္။function_element မ်ားအားရွင္းလင္းတိက်စြာ definition မၿပဳလုပ္ခဲ့လွ်င္ ၎တို႕အား အလိုအေလွ်ာက္ definition ၿပဳလုပ္သြားမည္ၿဖစ္သည္။အလိုအေလွ်ာက္ definition ၿဖစ္ေပၚေစနိဳင္မွဳ႕တို႕မွာ

  •        default constructor ,
  •        copy constructor,
  •        assignment operator,
  •        destructor
  •        addressing operator

Default constructor သည္ class ၏ object အား automatic variable မ်ားနွင့္တည္ရွိေစရန္ ၿပဳလုပ္လိုက္ၿခင္း ၿဖစ္သည္။

Example. Using the constructor without parameters.
class MyCls{  int a;
                   public:
                   MyCls(){ a=0; }       //constructor without parameter
                   Void Fn1(){ //body of a function Fn1(); }
                   Void Fn2(){ //body of a function Fn2(); }
                   ~MyCls() { cout<<”Destructor”; }  //destructor
                   };

Constructors with parameters(Конструкторы с параметрами)

Constructor မ်ားသည္ တန္ဖိုးမ်ားအား initialization ၿပဳလုပ္ရာတြင္ ၎တို႕ constructor_function ၏ body အတြင္းတြင္ မဟုတ္ပဲ ၎တို႕၏ parameter မ်ားအတြင္းတြင္ pass ၿပဳလုပ္နိဳင္သည္။
Example. Using constructor with parameters.

#include "stdafx.h"
#include <iostream>
#include <conio.h>
using namespace std;
class MyCls { int a, b;
               public:
              MyCls(int x, int y) {  a = x;
                                     b = y;
                                             }
              void Show_Dat()  { cout << a << ' ' << b << endl; }
            };
int _tmain(int argc, _TCHAR* argv[])
{        MyCls ob(10, 100);        // эта строка является сокращением записи
                                            // MyCls ob = MyCls(10, 100);
         ob.Show_Dat();
        _getch();
          return 0;
}

Example . Create a class, which is part of a closed string.
class str {char * s;    / / Pointer to the string
            public:
            str (char * word)  / / Constructor
            {S = new char [strlen (word) +1];
              strcpy (s, word);
            }
~ str () {delete [] s;}  / / Destructor
           void write ();                                                         / / Prototype function - element
          };
void str :: write ()     / / Definition of the function element
              {      cout << s;
              }


Default constructors(Конструкторы по умолчанию) 
Constructor သည္ argument တန္ဖိုးမ်ားအား default အေနၿဖင့္ ဖြဲ႕စည္းနိဳင္သည္။constructor တြင္ ၎၏ argument အားလံုးသည္ default ၿဖစ္ေနလွ်င္(သို႕)(မည္သည့္ argument မွသံုးရန္မလိုအပ္လွ်င္) ၎ constructor အား default constructor ဟုေခၚဆိုသည္။class တိုင္းအတြက္ default constructor တစ္ခုစီေတာ့္ တည္ရွိလိမ့္မည္ၿဖစ္သည္။ 
Example . Class Definition Cubic, assigns unit values ​​variables - length, width, height.

#include "stdafx.h"
#include <iostream>
#include <conio.h>
using namespace std;
class Cubic { public:
                         Cubic (int = 1, int = 1, int = 1);  // конструктор с умолчаниями
                         void setCubic (intintint);
                         void printCubic();
                         int volumeCubic();
                      private:
                         int length;
                         int width;
                         int height;
                   };
Cubic::Cubic(int len, int wid, int hei) // по умолчанию значения равны 1
    {  setCubic(len, wid, hei);
     }

void Cubic::setCubic(int l, int w, int h)  // некорректные значения явно (без
                                                       // умолчаний) устанавливаются равными 1
     {  length = (l > 0) ? l : 1;
         width = (w > 0) ? w : 1;
         height = (h > 0) ? h : 1;
     }
void Cubic::printCubic()
     {  cout << length << "x" << width << "x" << height << endl;  }
int Cubic::volumeCubic()
     { return length * width * height;}
int _tmain(int argc, _TCHAR* argv[])
{        Cubic c1, c2(3), c3(15, 12), c4(5, 6, 7), c5(-2, -3, -5);
   cout << "Все аргументы по умолчанию" << endl;
   c1.printCubic();
   c1.volumeCubic();
   cout << "Два аргумента по умолчанию" << endl;
   c2.printCubic();
   c2.volumeCubic();
   cout << "Один аргумент по умолчанию" << endl;
   c3.printCubic();
   c3.volumeCubic();
   cout << "Все аргументы заданы явно" << endl;
   c4.printCubic();
   c4.volumeCubic();
   cout << "Все аргументы заданы явно, но неправильно" << endl;
   c5.printCubic();
   c5.volumeCubic();
   _getch();
          return 0;
}

Default constructor ၏ argument မ်ားသည္ class definition အတြင္းရွိ function constructor ၏ prototype အတြင္းတြင္သာ ေၾကၿငာခြင့္ရွိသည္။

Pointers to object(Указатели на объекты) 
Pointer to object ဆိုသည္မွာ pointer အား အၿခား data_type အေနၿဖင့္ parameter အၿဖစ္ ေၾကၿငာ အသံုးၿပဳၿခင္းပင္ ၿဖစ္သည္။

Example.

#include "stdafx.h"
#include <iostream>
#include <conio.h>
using namespace std;
class MyCls {    int a;
                        public:
                          MyCls(int x) {  a = x; }
                          int get()   { return a; }
                    };
int _tmain(int argc, _TCHAR* argv[])
{  MyCls ob(150);           // создание объекта
   MyCls *pCls;              // создание указателя на объект
   pCls = &ob;                // передача адреса ob в pCls
   cout << "Значение, получаемое при использовании объекта:  "
           << ob.get() << endl;
   cout << "Значение, получаемое при использовании указателя:  "
           << pCls->get() << endl;
   _getch();
          return 0;
}

Overloading constructors(Перегрузка конструкторов)
Overload constructor အား ေအာက္ေဖာ္ၿပပါ အေၾကာင္းအရင္း သံုးရပ္ေၾကာင ့္အသံုးၿပဳရၿခင္းၿဖစ္သည္။
  •        to provide flexibility in program  
  •        support for arrays,
  •        to create a copy constructor
Class ၏ object မ်ားအား ေၾကၿငာၿခင္း ၿပဳလုပ္ၿခင္း နည္းအမ်ိဳးမ်ိဳးရွိသည္ၿဖစ္သည္။ထိုအမ်ိဳးမ်ိဳးေသာ
နည္းလမ္းမ်ားၿဖင့္ ေၾကၿငာရာတြင္ ၎တို႕အသံုးၿပဳမည့္ constructor design နွင့္ကိုက္ညီရန္ လိုအပ္ေပသည္။
သို႕မဟုတ္လွ်င္ translator(complier) သည္ error ၿဖစ္ေပၚလိမ့္မည္ၿဖစ္သည္။

Example. Overload the constructor to initialize the object is clearly the case of a specified value, and the value specified by default.

#include "stdafx.h"
#include <iostream>
#include <conio.h>
using namespace std;
class double_init {   int x;
                                 int y;
                               public:
                                 double_init(){ x = 0; y = 0;}
      double_init(int m, int n){ x = m; y = n;}
      void show_x_y() {cout << x << ' ' << y << endl;}
 };
int _tmain(int argc, _TCHAR* argv[])
{   double_init ob1(10, 100);   // объявление с явными значениями
   double_init ob2;                   // объявление без явного задания значений
   ob1.show_x_y();
   ob2.show_x_y();
   _getch();
          return 0;
}
Example. Overloaded constructor to initialize a single object and an array of objects.

#include "stdafx.h"
#include <iostream>
#include <conio.h>
#include <iomanip>
using namespace std;
class MyCls {        int x;
                       public:
MyCls()  { x = 0;}
MyCls(int n) { x = n;}
int  get_x() {return x;}
      };
int _tmain(int argc, _TCHAR* argv[])
{  MyCls ob1;                 // объявление объекта без явного задания значений
   MyCls ob2(10); // объявление объекта с явным значением
   MyCls ob3[10]; // объявление массива без явного задания значений
   MyCls ob4[10] = {1,2,3,4,5,6,7,8,9,10}; // объявление с явными значениями
   cout << "Объект ob1: " << endl;
   cout << ob1.get_x() << endl;
   cout << "Объект ob2: " << endl;
   cout << ob2.get_x() << endl;
   cout << "Массив ob3: " << endl;
   for (int i = 0; i < 10; i++)
       cout << setw(3) << ob3[i].get_x();
   cout << endl;
   cout << "Массив ob4: " << endl;
   for (int i = 0; i < 10; i++)
       cout << setw(3) << ob4[i].get_x();
   cout << endl;
   _getch();
          return 0;
}

Example. Overloaded constructor to create a dynamic array.

#include "stdafx.h"
#include <iostream>
#include <conio.h>
#include <iomanip>
using namespace std;
class MyCls {        int x;
                       public:
MyCls()  { x = 0;}
MyCls(int n) { x = n;}
int  get_x() {return x;}
      };
int _tmain(int argc, _TCHAR* argv[])
{  MyCls ob(12525);
   MyCls *obPtr;                                // объявление указателя
   MyCls ob_arr[10] = {1,2,3,4,5,6,7,8,9,10};     // объявление с явными //значениями
   cout << "Массив ob_arr: " << endl;
   for (int i = 0; i < 10; i++)  cout << setw(3) << ob_arr[i].get_x();
   cout << endl;
   obPtr = new MyCls[10];       // динамические массивы не инициализируются!
   if (!obPtr) { cout << "Ошибка выделения памяти" << endl;
                       return 1;
                    }
   cout << "Массив obPtr: " << endl;
   for (int i = 0; i < 10; i++)
       obPtr[i] = ob;
   for (int i = 0; i < 10; i++)
       cout << setw(3) << obPtr[i].get_x();
   cout << endl;
   _getch();
          return 0;
}

Assigning objects(Присваивание объектов)
အကယ္၍ Object မ်ားသည္ တူညီေသာ type ရွိလွ်င္ object တစ္ခုမွ အၿခား objectတစ္ခုဆီသို႕ assign ၿပဳလုပ္နိဳင္သည္။object A မွ object B ဆီသို႕ assign ၿပဳလုပ္လွ်င္ ပံုမွန္အားၿဖင့္ objectA ၏ data element မ်ားအားလံုးအား objectB ၏ data element မ်ားအေနၿဖင့္ bit-by-bit ၿဖင့္ copy ကူးယူလိုက္ၿခင္းၿဖစ္သည္။ operation ၿပဳလုပ္ၿပီးသြားခ်ိန္တြင္ objectA နွင့္ objectB တို႕တြင္ တူညီေသာ data element မ်ားတည္ရွိေနမည္ၿဖစ္သည္။
တူညီေသာ type ရွိမွသာ object မ်ားအား assing ၿပဳလုပ္နိဳင္သည္။(တူညီေသာ type ဆိုရာတြင္ class_type name တူညီရမည္ၿဖစ္ၿပီး physically အရတူညီၿခင္းကိုဆိုလိုၿခင္းမဟုတ္ေပ။ /* ေအာက္ေဖာ္ၿပပါ ဥပမာ နွစ္ပုဒ္အား ၾကည့္ပါက ရွင္းလင္းသြားလိမ့္မည္ ၿဖစ္သည္ */)။

Example .

#include "stdafx.h"
#include <iostream>
#include <conio.h>
using namespace std;
class MyClass {   int a, b;
                          public
                             void set(int i, int j)   {  a = i; b = j;  }
                             void show()   {  cout << a << ' ' << b << endl;  }
                        };
int _tmain(int argc, _TCHAR* argv[])
{  MyClass ob1, ob2;
    ob1.set(10, 5);
    ob2 = ob1;                 // все правильно
    ob1.show();
    ob2.show();
   _getch();
          return 0;
}
Example

#include "stdafx.h"
#include <iostream>
#include <conio.h>
using namespace std;
class MyClass {   int a, b;
                          public
                             void set(int i, int j)   {  a = i; b = j;  }
                             void show()   {  cout << a << ' ' << b << endl;  }
                        };
class YourClass {   int a, b;
                             public
                                void set(int i, int j)   {  a = i; b = j;  }
                                void show()   {  cout << a << ' ' << b << endl;  }
                           };
int _tmain(int argc, _TCHAR* argv[])
{   MyClass ob1;
    YourClass ob2;
    ob1.set(10, 5);
    ob2 = ob1;                 // ошибка трансляции
    ob1.show();
    ob2.show();
   _getch();
          return 0;
}
/* ပထမ ပုစၦာသည္ assign ၿပဳလုပ္မည့္ object နွစ္ခုစလံုး class name တူညီေသာ ေၾကာင့္ assign ၿပဳလုပ္နိဳင္ၿပီး ဒုတိယ ပုစၦာတြင္ assign ၿပဳလုပ္မည့္ object နွစ္ခုစလံုးသည္ physically အရ data_type မ်ားတူညီေသာ္လည္း class name မတူညီေသာေၾကာင့္ assign ၿပဳလုပ္လွ်င္ error ၿဖစ္ေပၚလိမ့္မည္ ၿဖစ္သည္။ */

The copy constructor(Конструктор копирования)
Copy constructor သည္ constructor overload မ်ားတြင္ အသံုးအမ်ားဆံုးေသာ တစ္ခုၿဖစ္သည္။copy constructor အသံုးၿပဳသည့္အခါတိုင္း new object တစ္ခုၿဖစ္ေပၚလာမည္ၿဖစ္ၿပီး တည္ရွိေနေသာ object နွင့္တူညိေသာ data_type အတိုင္း initialize ၿပဳလုပ္သြားမည္ၿဖစ္သည္။
C++ language တြင္ object တစ္ခုမွ အၿခားတစ္ခုဆီသို႕ assign ၿပဳလုပ္ရန္ နည္းလမ္း(၂) ခု၇ွိသည္။
  •      assignment
  •      initialization

Copy constructor အား initialization ၿပဳလုပ္ေသာအခါတြင္သာ အသံုးၿပဳေလ့ရွိသည္။assign နည္း အသံုးၿပဳေသာအခါ copy constructor အားအသံုးၿပဳရလိမ့္မည္မဟုတ္ေပ။
Initialization ၿပဳလုပ္ရန္ ေအာက္ေဖာ္ၿပပါ နည္းလမ္း(၃) ခုရွိသည္ၿဖစ္သည္။
  • when in the declaration one object is used to initialize another,
  • when passing an object as a parameter to a function,
  • creating a temporary object to return values ​​from functions.


Example. Suppose AnyClass declared class and an object of this class is ob1. Then copy constructor can be caused by the following operators:( AnyClass အား class တစ္ခုအၿဖစ္ ေၾကၿငာၿပီး ဟုယူဆၿပီး ၎ class ၏ object သည္ ob1 ဟုယူဆပါ။ထို႕ေနာက္တြင္ copy-constructor အား ေအာက္ေဖာ္ၿပပါ operator မ်ားအားၿဖင့္ အသံုးၿပဳနိဳင္သည္။)
AnyClass ob2 = ob1;               / / Ob one explicitly initializes two ob
AnyFn1 (ob1);                        / / Ob one passed as a parameter
ob2 = AnyFn2();               / / Ob 2 receives the returned value

Example. Suppose class is declared and one element of which is a pointer to int * p. Then, when you assign an object of this class( class ၏ တစ္ခုအား ေၾကၿငာခဲ့ၿပီး ၎ class ၏ element တစ္ခုသည္ int*p ဟူေသာ pointer အသံုးၿပဳထားသည္ဟု ယူဆပါ.ထို႕ေနာက္တြင္ ထို class ၏ object အား assign ၿပဳလုပ္လွ်င္ ေအာက္ပါအတိုင္းၿဖစ္မည္..)
second = first;
the most critical is the assignment operator, present in the code listing:(မ်ားေသာအားၿဖင့္ assignment operator ၿဖင့္အသံုးၿပဳလွ်င္ ေအာက္ေဖာ္ၿပပါ code အတိုင္းၿဖစ္လိမ့္မည္ၿဖစ္သည္)
second.p = first.p;
( ထိုသို႕အသံုးၿပဳၿခင္းသည္ pointer p မွ define ၿပဳလုပ္ထားေသာ array အား copy ၿပဳလုပ္ၿခင္းမဟုတ္ပဲ pointer ကိုသာ တိုက္ရိုက္ copy ကူးယူၿခင္းၿဖစ္သည္)
The problem occurs at the time of operation call (ေအာက္ေဖာ္ၿပပါ operation အတိုင္း call ေခၚလွ်င္ problem ၿဖစ္လိမ့္မည္ၿဖစ္သည္)
delete [] second.p;
removing the array pointed to by the pointer p. Then, the result of the operation(pointer p ၿဖင့္ point ၿပဳလုပ္ထားေသာ array ကို ပယ္ဖ်က္ၿခင္းၿပဳလုပ္ေသာ operation ၿပီးပါက ေအာက္ေဖာ္ၿပပါ ရလဒ္အတိုင္း ၿဖစ္ေပၚလိမ့္မည္ၿဖစ္သည္။
delete [] first.p;
အကုန္လံုးအား ၿဖတ္ၿပီးသကဲ့သို႕ ၿဖစ္လိမ့္မည္ၿဖစ္သည္။

ထိုကဲ့သို႕ေသာ ၿပသနာမ်ိဳးအား ေၿဖရွင္းရန္အတြက္ copy constructor အားေကာင္းမြန္စြာအသံုးၿပဳနိဳင္သည္ ေၿဖရွင္းရန္အတြက္ array ၏ address အား copy ကူးယူမည့္အစား copy constructor သည္ အၿခား array တစ္ခုအား တည္ေဆာက္လိုက္ၿပီး မူလ array ၏ element တန္ဖိုးမ်ားအား အသစ္တည္ေဆာက္လိုက္ေသာ  array ၏ address နွင့္ duplicate ၿပဳလုပ္ၿခင္းအားၿဖင့္ တန္ဖိုးအားလံုးတူညီသြားလိမ့္မည္ၿဖစ္သည္။ 
ထို copy constructor ၏ syntax သည္ ေအာက္ပါအတိုင္းၿဖစ္သည္။
classname (const class_name & obj)
{constructor_body
}
/* obj သည္ တစ္ၿခား object အေနၿဖင့္ initialize ၿပဳလုပ္ရန္အသံုးၿပဳမည့္ address တစ္ခုၿဖစ္သည္။ */

Example.Creating a copy constructor for the object that contains as one of its members to a dynamic array.

#include "stdafx.h"
#include <iostream>
#include <conio.h>
#include <iostream>
using namespace std;
class array {  int *Arr_Ptr;
                      int size;
                    public:
                      array (int sz)      // конструктор
                          {  Arr_Ptr = new int[sz];
                              if (!Arr_Ptr) exit (1);
                              size = sz;
                              cout << "Ordinary constructor" << endl;
                          }
                      array(const array &a);          // прототип конструктора //копирования
                      ~array() { delete [] Arr_Ptr; }         // деструктор
                      void put(int i, int j)      {  if (i >= 0 && i < size) Arr_Ptr[i] = j;    }
                      int get(int i)    {  return Arr_Ptr[i];  }
                  };
// конструктор копирования
array :: array(const array &a)
   {  int i;
       Arr_Ptr = new int[a.size];          // выделение памяти для копии массива
       if (!Arr_Ptr) exit(1);
       for (i = 0; i < a.size; i++) Arr_Ptr[i] = a.Arr_Ptr[i];        // копирование содержимого
       cout << "Copy constructor" << endl;
   }
int _tmain(int argc, _TCHAR* argv[])
array arr(10);    // вызов обычного конструктора
    int i;
    for (i = 0; i < 10; i++)  arr.put(i, i);
    for (i = 0; i < 10; i++)  cout << arr.get(i);
    cout << endl;
    array new_arr = arr;           // вызов конструктора копирования
    for (i = 0; i < 10; i++)  cout << new_arr.get(i);
   _getch();
          return 0;
}

translated by zmk@miet51


No comments:

Post a Comment