J
Jess
Hello,
Sometimes declarations are all what we need when we define/declare
classes (or functions?), but sometimes we need definitions. I learned
that if we define a class (B) that has an object (a_obj) of a class
type (A), then we need to define A as well, but if B has a pointer to
A, then we only need to forward declare A. I was told this is because
the compiler needs to see the implemenation of A when allocating
memory for a_obj. However, I think compilers won't allocate any
memory until we create an object of class B. Therefore, if I have
a .cpp file
class A;
class B{
A a_obj;
};
then it seems ok to forward declare A, because there's no object of
class B created. So in this case, why do I still have to define A (or
include it's header file)?
Similarly, we can forward declare A if we only declare a function like
A f(A a);
but we need A's implemenation when we define "f"
A f(A a){...}
If my .cpp file only has f's definition without any program that calls
"f", then shouldn't it be perfectly safe to forward declare A?
I guess my general question is when can we use declarations without
definitions?
Another question about forward declaration is that why do we use
class A;
instead of
extern class A;
I think the latter says A is a class defined somewhere else.
Thanks a lot,
Jess
Sometimes declarations are all what we need when we define/declare
classes (or functions?), but sometimes we need definitions. I learned
that if we define a class (B) that has an object (a_obj) of a class
type (A), then we need to define A as well, but if B has a pointer to
A, then we only need to forward declare A. I was told this is because
the compiler needs to see the implemenation of A when allocating
memory for a_obj. However, I think compilers won't allocate any
memory until we create an object of class B. Therefore, if I have
a .cpp file
class A;
class B{
A a_obj;
};
then it seems ok to forward declare A, because there's no object of
class B created. So in this case, why do I still have to define A (or
include it's header file)?
Similarly, we can forward declare A if we only declare a function like
A f(A a);
but we need A's implemenation when we define "f"
A f(A a){...}
If my .cpp file only has f's definition without any program that calls
"f", then shouldn't it be perfectly safe to forward declare A?
I guess my general question is when can we use declarations without
definitions?
Another question about forward declaration is that why do we use
class A;
instead of
extern class A;
I think the latter says A is a class defined somewhere else.
Thanks a lot,
Jess