I'm not sure where I'm going wrong here. If I have created a class (Class A) which I have declared and am using in my main() function and I want to declare a second class (Class B) which can be used by Class A and be accessed from withing my main function then how do I do this? I keep getting SigSev errors when I try to run the program without the extern keyword and when I do use it it won't compile.
Should I be using an extern keyword and if so do I have to put int into separate headers or is there another approach to resolving this?
I have to be abstract to keep this simple. Can't put any of the original code online.
eg.
//Class B declaration.
B *myB; // no error when compiling but a runtime sigsev error occurs
// if I declare like this.
extern B *myB; // program won't compile.
Class A
{
A(int x, int y, int z);
~A();
int somefunction()
{
// From here, I can't access Class B as the below causes a runtime error.
int x = myB->size(); // some random exercise using Class B.
return x;
}
};
int main()
{
A *myA = new A(x,y,z); // works fine and instantiates a new class.
//But lets say I'm using a class from an external library called Class B.
// I want to use it inside the definition of class A and in my main function.
B = new B(x,y);
}
Don't use extern keyword. Add assert(myB); before line 17 and #include <cassert> . Run it.
Do it say "assertion failed"?
If yes, error in your program. Variable myB is not initialized, but you try to use it.
If no, there is error in class B. Is it your class, or you use class written by someone else?
Thanks for that.. That helped.
I've never used assert before but will going forward.
I had a mistake in my code which caused this issue. I can readily declare variables globally, which can be used in a class definition, but one of my class pointers I had not allocated space for in memory (malloc). So when I went to use it in the class it kept failing.
but one of my class pointers I had not allocated space for in memory (malloc).
Unless your class in Standard Layout, you should not use malloc to allocate memory for it (unless you will handle aligment problems and use placement new manually after that).