C++ How to have an instance of the same class as an attribute?

0

I am trying to have a class called Cube have an attribute that is an instance of another cube.

Here are the important parts of my Cube.cpp:

bool hasSon = false;
Cube* son;
Cube::Cube()
{
}
void Cube::setSon(Cube* s)
{
    son = s;
    hasSon = true;
}
void Cube::draw() {if(hasSon) {son->draw()}}

And here is my cube.h:

    class Cube
{
public:
    Cube();
    bool hasSon;
    Cube* son;
    void setSon(Cube* son);
    void draw();
};

I am instancing the cube and using setSon(); like so:

Cube* base = new Cube();
Cube* base2 = new Cube();
base->setSon(base2);

The problem I am getting is that I get memory erros, even if I never call setSon(); what would be the correct way to set the son attribute?

Here is my error:

    Exception thrown at 0x00DA3716 in CG_Demo.exe: 0xC0000005: Access violation reading location 0xCDCDCDF1.
Unhandled exception at 0x00DA3716 in CG_Demo.exe: 0xC0000005: Access violation reading location 0xCDCDCDF1.
c++
class
reference
asked on Stack Overflow Oct 29, 2018 by IvanHid • edited Oct 29, 2018 by IvanHid

1 Answer

0

You don't need hasSon. You can initialize the pointer to nullptr and use that to test if a Cube* has been set. As your provided code is incomplete its hard to say why you get the error, but this works,

class Cube
{
public:
    Cube();
    //bool hasSon;
    Cube* son;
    void setSon(Cube* son);
    void draw();
};

Cube::Cube() : son(nullptr)
{}

void Cube::setSon(Cube* s)
{
    son = s;
}

void Cube::draw() 
{
    if(son) 
        son->draw();
}


int main()
{
    Cube* base = new Cube();
    Cube* base2 = new Cube();
    base->setSon(base2);
    base->draw();
}

Demo

answered on Stack Overflow Oct 29, 2018 by rmawatson

User contributions licensed under CC BY-SA 3.0