JuliusvM
JuliusvM

Reputation: 335

Creating an object within another class C++

I'm getting a strange runtime error that I simply cannot comprehend. I'm making an object of my class Circle, which has the following default constructor:

    Circle::Circle()
{
    this->radius = 0;
    this->center->setX(0);
    this->center->setY(0);
}

The variables that are being are initialized are:

private:
    double radius;
    Point *center;
};

When I try to make an object of the class circle, I get a runtime error. Now I only get this error when the Point objectis declared dynamically. Is there anything wrong with my syntax? When I declare the Point in my Circle class like this instead:

Point center;

And initializes it like this instead:

Circle::Circle()
{
    this->radius = 0;
    this->center.setX(0);
    this->center.setY(0);
}

It works. Why do I get these errors when I create the object dynamically? Can I not use two "->" like in the first example?

This is my first post, I hope this is not a too stupid question. Thanks in advance.

Upvotes: 0

Views: 132

Answers (3)

ForeverStudent
ForeverStudent

Reputation: 2537

The problem occurs because center is a pointer that does not have memory allocated to it. Since no such object exists,

Circle::Circle()
{
    this->radius = 0;
    this->center = new Point; //call the appropriate Point constructor
    this->center->setX(0); //now these are valid
    this->center->setY(0);
}

also notice since center is actually a pointer in your implementaion, center.setX(0) is invalid, you should do center->setX(0) instead

Upvotes: 0

πάντα ῥεῖ
πάντα ῥεῖ

Reputation: 1

You should better use

Circle {
private:
    double radius;
    Point center; // <<<<<<< No pointer here
};

You don't need a pointer.

The problem with your current code is that no memory is allocated for your pointer variable. I'd also not recommend to do it (e.g. with center = new Point()). As mentioned, it's not necessary.

Also you don't need this-> to access class members. Just use the member initializer list in your constructor:

Circle::Circle() : radius(0), center(0,0) {
}

Upvotes: 1

NathanOliver
NathanOliver

Reputation: 181008

center is a pointer. If you do not allocate any memory for it then you cannot access it as it does not point to a valid object. To get a valid object we would use

Circle::Circle() : radius(0), center(new Point)
{
    center->setX(0);
    center->setY(0);
}

If Point has a constructor that takes x and y then you could even use

Circle::Circle() : radius(0), center(new Point(0, 0)) {}

But I do have to ask if you even need a pointer here. If not then you could have

Circle::Circle() : radius(0),
{
    center.setX(0);
    center.setY(0);
}
// or
Circle::Circle() : radius(0), center(0, 0) {}

Upvotes: 0

Related Questions