Rule of Three. Copy Constructor, Assignment Operator Implementation

Rule of Three. Copy Constructor, Assignment Operator Implementation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
    #include <iostream>
    using namespace std;

    class IntPart
    {
    public:
     IntPart(); // default constructor
     IntPart(int n); 

    private:
     unsigned int* Counts;
     unsigned int numParts;
     unsigned int size;
    };

    IntPart::IntPart()
    {
     Counts = new int[101] (); // allocate all to 0s
     numParts = 0;
    }

    IntPart::IntPart(int n)
    {
     Counts = new int[n+1] (); // allocate all to 0s
     Counts[n] = 1;
     numParts = 1;
    }

    int main ()
    {
     IntPart ip2(200);
     IntPart ip3(100);
 
     IntPart ip(ip2); // call default and copy constructor?

     IntPart ip4; // call default constructor
     ip4 = ip3;
 
     system("pause"); return 0;
    }


Obviously this needs to have the rule of three.
Could you help me define them?

Q0.
IntPart ip(ip2);
Does this one creat ip object calling default constructor
and after that, call copy constructor?
Am I right?

Q1. Define destructor.
1
2
    IntPart::~IntPart()
    { delete [] Counts; }


is it correct?

Q2. Define copy constructor.
1
2
3
    IntPart::IntPart(const IntPart& a)
    { // how do I do this? I need to find the length... size.... could anybody can do this?
    }


Q3. Define assignment operator.
1
2
3
4
5
6
7
8
    IntPart& IntPart::operator= (const IntPart& a)
    {
      if ( right != a)
      {
        // Anybody has any idea about how to implement this?
      }
      return *this;
    }


Thanks,
I would appreciate it!
Q0:
No, ip2 is already constructed. So only copy constructor is called.
If it was IniPart ip = IniPart(10); default constructor might be called (I do not remember what standard says)

Q1:
Correct

Q2:
You need to allocate array (as in default constructor) copy all elements of array in a to your new class and copy all variables. Also you should set size variable in your constructors, so you will know size of your array.
1
2
3
4
5
6
    IntPart::IntPart(const IntPart& a)
    {
        size = a.size;
        numParts = a.numParts;
        //allocate array of size size here and copy all values.
    }


Q3:
Assign all variables of this like in copy constructor. Do not forget to allocate new array instead of copying the pointer.
Last edited on
Topic archived. No new replies allowed.