-1

Rule of Three. Copy Constructor, Assignment Operator Implementation

#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.

IntPart::~IntPart()
{ delete [] Counts; }

is it correct?

Q2. Define copy constructor.

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.

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!

john
  • 85,011
  • 4
  • 57
  • 81
user2310042
  • 85
  • 2
  • 4
  • 3
    There are literally *millions* of sample object implementations that follow the Rule of Three on the web. Thousands on this site alone. See that "Related" list on the right? try clicking it. vtc. – WhozCraig Apr 23 '13 at 06:39
  • Probably allocate space for `Counts` if needed and copy from `a.Counts`. Possibly deleting the old `Counts` first (if it is too small). – Bo Persson Apr 23 '13 at 06:42
  • possible duplicate of [What is The Rule of Three?](http://stackoverflow.com/questions/4172722/what-is-the-rule-of-three) – Tony Delroy Apr 23 '13 at 07:23
  • 1
    Also remember the Rule of Zero. By using resource-management types that already implement these three (in this case, `std::vector`), your own types won't need any of them. – Mike Seymour Apr 23 '13 at 07:43

1 Answers1

3

Q0. No, this calls the copy constructor only. That's a pretty big misunderstanding, objects are only ever constructed once.

Q1. That's correct

Q2. Presumably you are meant to store the array size in size. E.g.

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

If you don't store the array size somewhere, your copy constructor will be impossible to write.

Q3. I would look up the copy and swap idiom. This lets you write the assignment operator using the copy constructor.

Community
  • 1
  • 1
john
  • 85,011
  • 4
  • 57
  • 81