Copy Constructor

This is the sample here in cplusplus tutorial about copy constructor. I am trying to understand on which initialization the copy constructor was needed to be used?... I saw that without it the program crashes on run time but i cannot fully understand it. Can someone explain it to me in a beginners way. I have made a search already about it and im a bit still confused.

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
#include <iostream>
#include <string>
using namespace std;

class Example5 
{
    string* ptr;
public:
    Example5 (const string& str) :
	ptr(new string(str)) 
	{
		
	}
    ~Example5 () 
	{
		delete ptr;
	}
    // copy constructor:
    Example5 (const Example5& x) : 
	ptr(new string(x.content())) 
	{
		
	}
    // access content:
    const string& content() const 
	{
		return *ptr;
	}
};

int main () {
  Example5 foo ("Example");
  Example5 bar = foo;

  cout << "bar's content: " << bar.content() << '\n';
  return 0;
}
WIthout explicitely defined copy constructor compiler generates one, which perform shallow copy: copies each member value.

As you have a pointer here, your copy will contain pointer with same value original has.
So those two pointers (original and copy) point to the same string. And when it is time for destructor, copy deletes string it points to, then original tries to delete same string. Deleting already deleted stuff leads to undefined behavior.
on the main function, does the copy constructor that was on that code also performing? and on what part?
Line 33: Example5 bar = foo; it is copy initialization and is exactly the same if we write Example5 bar(foo);
if i dont have a copy constructor on that code, it will create a default copy constructor when the code Example5 bar = foo; initialize? sorry for the too much question. Been having trouble understanding it...
it will create a default copy constructor when the code Example5 bar = foo; initialize?
Yes, compiler creates a copy constructor on first request if it wasn't defined earlier.
Thank you so much...
Another thing... When does the copy constructor needs to be created when you code?... is it always needed whenever you have pointers? or whenever you have pointers and decided to delete it after a while to free up memory?
http://en.cppreference.com/w/cpp/language/rule_of_three

Whenever you have a resource you eed to handle specially (memory and pointer to it is an example of such resource)
Topic archived. No new replies allowed.