Omar Moya
Omar Moya

Reputation: 43

Getting pointer attribute value

im working on this exercise about operators overloading and references. The problem is that when i ask for the value in the "itsRadius" pointer attribute of the SimpleCircle class, im getting strange values... Also, if i have this destructor:

SimpleCircle::~SimpleCircle()
{
    delete itsRadius;
    itsRadius = 0;
}

i get the "_block_type_is_valid(phead-> nblockuse)" error. The idea is having this detructor to delete the memory allocated for the attribute in the class... I know that this error is triggered when i delete two times something that was already deleted, but i dont know where this happened... is that so?

here is the hole code of the exercise:

#include <iostream>

using namespace std;

class SimpleCircle
{
    public:
    SimpleCircle();
    SimpleCircle( int );
    SimpleCircle( SimpleCircle& );
    ~SimpleCircle();

    void setRadius ( int );
    int getRadius() const { return *itsRadius; };

    const SimpleCircle& operator++();
    const SimpleCircle operator++( int );
    SimpleCircle& operator=( const SimpleCircle& );

    private:
    int *itsRadius;
};

SimpleCircle::SimpleCircle()
{
    itsRadius = new int(5);
}

SimpleCircle::SimpleCircle(int radius)
{
    itsRadius = new int(radius);
}

SimpleCircle::SimpleCircle( SimpleCircle & rhs )
{
    int val = rhs.getRadius();
    itsRadius = new int (val);
}

SimpleCircle::~SimpleCircle()
{
    delete itsRadius;
    itsRadius = 0;
}

const SimpleCircle& SimpleCircle::operator++()
{
    ++itsRadius;
    return *this;
}

const SimpleCircle SimpleCircle::operator++(int)
{
    SimpleCircle temp(*this);

    ++(itsRadius);
    return temp;
}

SimpleCircle& SimpleCircle::operator=( const SimpleCircle& rhs)
{
    if (this == &rhs) { return *this; }
    *itsRadius = rhs.getRadius();
    return *this;
}

void main()
{
    SimpleCircle a, b(9);
    a++;
    ++b;
    cout << a.getRadius();
    cout << b.getRadius();
    a = b;
    cout << a.getRadius();
    cout << b.getRadius();
    system("pause");
}

Upvotes: 1

Views: 1162

Answers (1)

Marius Bancila
Marius Bancila

Reputation: 16328

I see no reason for you to have the radius as a pointer to int. It's over complicated and as you see you get into various problems.

Besides the problem you mentioned you have another one:

++itsRadius;

You are incrementing the pointer, but you should increment the object it points to.

++(*itsRadius);

Just use an int value and get rid of all the headache.

Upvotes: 3

Related Questions