I'm trying to make this code as generic as possible to help future wanderers.
A.h
class A {
protected:
A* pointToAnother;
public:
A();
func();
}
A.cpp
A::A() {
pointToAnother = nullptr;
}
A::func() {
// does something
}
B.h
#include "A.cpp" //Using A.h gave me linking errors
class B {
protected:
A* pointToA;
public:
B();
do_something();
}
B.cpp
B::B() {
A tmp;
pointToA = &tmp;
}
B::do_something() {
pointToA->func();
}
int main() {
B test;
B.do_something();
}
When do_something()
is called, before pointToAnother->func()
runs, pointToA->pointToAnother
correctly points to 0x00000000
. However, once func()
runs, pointToAnother
is now pointing at 0xcccccccc
BEFORE running what's inside of func()
, which breaks my program.
I tried implementing the rule of three, thinking the bug had something to do with destruction, but that had no dice. I ran into a similar problem in another program (modifying an object in a vector by calling a function of said object, only for the previous position in the vector to now be pointing to 0xcccccccc
) that I gave up on.
Thanks