can someone check if my assignment operator looks ok

can someone tell me if my assignment operator looks ok. i am suppose to delete in the assignment right. sorry i did the copy constructor now im doing the assignment operator. no more operators today after this :)

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
47
48
49
50
51
52
53
#include <iostream>
#include <string>

using std::cout;
using std::endl;
using std::cin;

class stickfigure
{
public:
    stickfigure(int j)
    : test(new int(j))
    {}

    stickfigure(const stickfigure& ref)
    : test(new int(*ref.test))
    {}

    stickfigure& operator = (const stickfigure& ref)
    {
        if (this != &ref)
        {
            delete test;
            test = new int(*ref.test);
        }

        return *this;
    }
    virtual ~stickfigure(){ delete test;}

    void print() const{cout << *test << endl;}

private:

    int* test;
};

int main(int argc, char** argv)
{

    stickfigure stickone(76);
    stickone.print();

    // copy
    stickfigure sticktwo(stickone);
    sticktwo.print();

    // assignment
    stickfigure stickthree = sticktwo;
    stickthree.print();

}
Last edited on
got an answer from a pretty cool site. it is ok. thanks for looking.
why would you delete your int, only to reallocate it?

Why not just do this:

1
2
3
4
5
6
stickfigure& operator = (const stickfigure& ref)
    {
        *test = *(ref.test);

        return *this;
    }



Or for that matter, why is test even dynamically allocated? Why not just use an int?
this thread is a little old but i wanted to answer. its because it was an exercise for myself. just so i know how. i know i could have used a regular int but that wasnt what i was trying to learn. design wasnt even the issue. i was trying to learn how to deal with assignment operators and copy ctors when your class contained a object on the heap and form. i looked at your code and agree its more straightforward. i actually had used that at one point but i thought it wasnt checking for self assignment. after reading the c++ faq i realized there is more then 1 way to check for self assignment so its ok. i will use your way in the future if i can.
Last edited on
Topic archived. No new replies allowed.