Bit said:
What's wrong with this:
//file1.h
Class A {
public:
A(){i=1;}
~A(){;}
void doThis(void){;}
void doThat(void){;}
private:
int i;
};
//file2.h
#include "file1.h"
A a;
Class B {
public:
B(){
//a = new A(); //will not compile
//a.doThis();
}
~B(){;}
};
Anyone know why I can't use a (type A) in class B ?
You can. Your problems don't arise from that.
First, you've got a variable at file scope in an h file.
You don't usually want that. If you include file1.h in
more than one .cpp file, you get trouble. If you want
an instance of class A at file scope, you need to
declare it in the .cpp file where you want it, not in
a header file.
Next, as somebody pointed out, you've got a call
to new and you are putting the result into a non-pointer.
Calls to new return pointers to allocated memory.
Read up on pointers.
Next, you are doing something pretty whack even
if you do change the variable a to a pointer, and
even if you do have only one instance of a at
file scope. You are assigning a pointer to a "newed"
instance to the variable a. But the variable a is
outside the scope of the class B that is doing it.
So, the second time you do this, you will wind
up with a resource leak.
Probably what you want is something like so. First,
drop the variable a entirely. Then add a pointer as
a member of class B. Then add the appropriate
thing to the dtor of B to avoid the memory leak.
#include "file1.h"
Class B {
public:
B(){
pa = new A(); //will not compile
pa->doThis();
}
~B(){delete pa;}
private:
A * pa;
};
Socks