I have a class called foo1 and in foo1.h I have
class foo1
{
public:
int var;
foo1();
};
There is also another class called foo2, in which I have an object based on foo1:
class foo2
{
public:
foo1 *afoo1;
foo2();
void func1(int,int);
};
My question is that how I can have access to afoo1->var. If I use afoo1->var in foo2.cpp, everything looks fine and it compiles with no error. But when I run it in the command prompt window, a window pups up and asks to close the program. I guess this is because I am violating memory access, the cause of which could be afoo1->var.
Can anyone help me with this?
Thanks
Extra Note
I make a dll file from foo2, and use it in another program, the source code of which I do not have any access to. Just to make things clarified a bit more.
Answer
I had made two mistakes. The first one was that I was referencing to Null. afoo1 = new foo1(); in the constructor of foo2 took care of that.
The second one was that I had not included foo1.cpp in my makefile. I know, stupid mistake.
You need to do
foo2Instance->afoo1->var, inside the foo2 methods this will just beafoo1->var. If that is crashing it’s more likely because you’re not initializingafoo1in foo2’s constructor.Make sure you have
#include "foo1.h"in foo2.hIf you’re getting a NullReferenceException it’s likely because you’re missing that line in the constructor.
afoo2->afoo1is fine whenafoo1 == NULLhowever, if you try to access a property ofafoo1you will crash every time.NULL->somePropertyis never okay.