Copy Constructor

What is wrong with my copy constructor? If I change the string datatypes to int it works...IDK..

update: okay so the string never allocated memory on the heap...but thats weird because i did not have to declare new int to have the program work.?

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

class Person{

private:
    string* name;
    
public:
   Person(string n)
    {
        *name = n;
    }
    Person(const Person &p)
    {
        name = p.name;
    }
    void changeName(string s)
    {
        *name = s;
    }
    void print()
    {
        cout << *name << endl;
    }
};

int main()
{
    Person p("my name");
    Person p2 = p;
    
    p.print();
    p2.print();
    
    p.changeName("asdf");
    
    p.print();
    p2.print();

    
    return 0;
}


SOLUTION:

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
41
42
43
44
45
46
#include <iostream>
#include <string>
using namespace std;

class Person{
    
private:
    string* name;
    
public:
    Person(string n)
    {
        name = new string(n);
        //*name = n;
    }
    
    Person(const Person &p)
    {
        name = p.name;
    }
    void changeName(string s)
    {
        *name = s;
    }
    void print()
    {
        cout << *name << endl;
    }
};

int main()
{
    Person p("my name");
    Person p2 = p;
    
    p.print();
    p2.print();
    
    p.changeName("asdf");
    
    p.print();
    p2.print();
    
    
    return 0;
}
Last edited on
Why are you storing pointer to string? Fist of all you do not need it. Second: you have a leak because you never written a destructor. Change string* to string and you will not need explicitely define copy constructor and destructor. Also move constructing and move assigment would be generated and work as intended.

but thats weird because i did not have to declare new int to have the program work.?
Welcome to the world of undefined behavior. When undefined behavior happens your program may work, may not work, may work strangely, explode your computer or summon demons from your nose. Al these behaviors are acceptable by C++ standard.

Mandatory reading:
http://blogs.msdn.com/b/oldnewthing/archive/2014/06/27/10537746.aspx
http://blog.llvm.org/2011/05/what-every-c-programmer-should-know.html
thanks i didn't write a destructor cause it was just a 2 second thing i wanted to write to see if it works..
Topic archived. No new replies allowed.