Very simple question – how can I access data for a struct that lives inside the heap?
Additional information:: I have a class called “A” and a struct within this class called “B”. Every “B” that is created will live on the heap. Class “A” is intended to have a vector of “B”‘s as a private data member (ie. the class “A” can hold many “B”‘s). I have a method in class “A” that will add another new instance of “B” in the vector that “A” has. I also have another method in class “A” that will update every single element that is in the vector of “B” instances. My questions are:
How do I use the getters and setters within my struct?
Here is some code that might help (note: grafix.h is a graphical library)
//.h file
#pragma once
#include <vector>
#include "grafix.h"
class A
{
public:
~A();
A();
void addB();
void updateB();
private:
struct B
{
public:
~B()
{
delete p_b;
p_b = 0;
}
B()
{
p_b = new B; //I need this here
p_ball->x = 0;
p_ball->y = 0;
p_ball->r = 15;
}
void setxy(int X, int Y)
{
//What does this look like?
//This?
x = X; //?
y = Y;
}
int retx()
{
//Likewise.... ?
return x; //?
}
int rety()
{
return y;
}
void update()
{
draw();
//Movement code taken out for time being
}
private:
int x,y; //xy
int r; //radius
B* p_b; //pointer to object, do I need this?
void draw()
{
draw_circle_filled(x,y,r);
//how can I access the data within the struct B here?
//do I use the getters/setters? dereference??
}
};
vector <Ball*> bs; //Holds all of the B's that have been created
};
And then the .cpp file that has the methods. This is where I have my question, am I typing in the right syntax??
#include "A.h"
A::A()
{
addB();
}
void A::addB()
{
B* b;
bs.push_back(b);
}
void A::updateB()
{
for(int i = 0; i < bs.size(); i++)
{
bs[i]->update();
}
}
this is criminal :
B* b is NOT initialized.
Having a reference on it in you container is criminal: dereferencing this address doesnt make sense and is undefined behaviour / crash.
you should assign this way:
Edit: as Kevin commented below as is there is still a memory leak. You’d rather use a container of
std::shared_ptr<B>. This way the B oject will be deleted when nobody keeps a shared_ptr pointing to it.