Reputation: 6526
Does C++ has any other alternative to forward declaration? For example, I have a class B that uses class A.
class B
{
public:
void set_classA_val( A &b);
};
class A
{
private:
int example;
};
Is there any alternative to resolve this compilation issue rather than placing the class A above class B? Do we have any other alternative? Is forward declaration is the only solution?
Upvotes: 3
Views: 133
Reputation: 311048
Any name shall be declared before its using. If you do not like the following code
class A;
class B
{
public:
void set_classA_val( A &b);
};
then you can use elaborated type name in the parameter declaration of member function set_classA_val
class B
{
public:
void set_classA_val( class A &b);
};
Upvotes: 2
Reputation: 15870
There are a few options, but without more information about your goals, it is hard to tell you which is the best. Forward declaration, move the definition of A
, and making B
a template class are some of the options. Presuming you are familiar with the 2 former, the latter would look something like:
template<typename T>
class B
{
public:
set_value(T& t);
};
And you would declare it for use using:
B<A> ba;
As jrok mentioned, you can also make the function itself a template - but the use would depend on how B
is using the parameter (e.g. if the type is needed for other functions as well, it would probably be better to make the whole class utilize it).
Upvotes: 1
Reputation: 6030
Yes,
if You don't want to place A before B, then forward declaration is the only solution in that case (if You don't want to change definition of B - see Zac Howland answer for other ideas that change B). There is nothing wrong with that. Somehow, methods from B needs to know what A is (in that case it is a class). Either, compiler will figure it out by finding A definition or You will help the compiler with forward declaration.
Upvotes: 4