Define both copy constructors and Assignment Operator

hi there

:) I need fact check if this is makes sense ( I think it does but .....)

".... when you overload the assignment operator, you must always want to overload the copy constructor as well (and vice versa). You don't want your custom copying routine used in some situations and the default member by member scheme used in others. Even if you don't think you'll use one or the other, you may find that compiler using them in non obvious situation, such as passing an argument to a function by value, and returning from function by value.
In fact if the constructor to a class involves the use of system resources such as memory or disk files, you should almost always overload both the assignment operator and the copy constructor, and make sure they do what you want."

thanks :)
It does make sense - but most of the time the destructor should be included in that list too.

This is the rule of three: if you must define one of the copy constructor, copy assignment operator, or destructor, you should usually define them all.
http://en.cppreference.com/w/cpp/language/rule_of_three
Last edited on
Thank you mobzzi :) I will keep this in mind!!
that is one great example of the rule of three! I never heard of this before.
There is one exception I can think of when you want a destructor but don't need copy ctor or assignment operator. For example sometimes you want to know how many objects are in memory.
1
2
3
4
5
6
7
8
9
10
11
class Sprite
{
public:
  Sprite(){mCount++;}
  virtual ~Sprite() {mCount--;}
  static size_t getCount() {return mCount;}
private:
  static size_t mCount;
};

size_t Sprite::mCount = 0;
how many objects are in memory

Hmm, copy ctor is a ctor too and constructs one more object ...
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
#include <iostream>

class Sprite
{
public:
  Sprite(){mCount++;}
  virtual ~Sprite() {mCount--;}
  static size_t getCount() {return mCount;}
private:
  static size_t mCount;
};

size_t Sprite::mCount = 0;

int main()
{
  Sprite * a = new Sprite;
  std::cout << Sprite::getCount() << " one\n";
  Sprite * b = new Sprite( *a );
  std::cout << Sprite::getCount() << " two\n";
  delete a;
  std::cout << Sprite::getCount() << " one\n";
  delete b;
  std::cout << Sprite::getCount() << " null\n";
  return 0;
}

1 one
1 two
0 one
18446744073709551615 null
Hmm, copy ctor is a ctor too and constructs one more object ...

You are right, just forgot to delete the copy ctor.
Topic archived. No new replies allowed.