Get rid of the redundant A*
in the constructor. What this does is create a new, local variable with the same name as your class member. So the real B::data
never gets anything assigned to it, and when you try to delete it, things blow up. To add insult to injury, the new A()
you assign to the local data
will be leaked (well; it would be leaked if the program didn't crash).
class B{
private:
A* data;
public:
// Allocating new memory
B (){
data = new A();
}
//giving memory back
~B(){
delete data;
}
};
That solves the immediate problem, but as juanchopanza noted in the comments, you will still run into problems if you try to copy this object.