What is the difference between the two methods?
Sometimes when I get compile-time errors complaining that the compiler does not recognize some class types in functi
The compiler must know the type of the function parameter. Since you obviously don't provide a definition for example by including the header of Client
you have to provide a forward declaration. That is what you do in the second example (in an unusual way), so the compiler knows, that Client is a class. Since you only use a Pointer, the declaration is enough and you don't need the definition at this point.
If you need to prefix your parameter with class
, it means that the compiler is not yet aware of a class called Client
. Take the following contrived example:
int main(int argc, char *argv[])
{
MyClass m;
return 0;
}
class MyClass
{
};
Because MyClass
is declared AFTER the main function, the main function is not aware of the class called MyClass
when it tries to create the variable m
, and your program would refuse to compile.
To solve this, you would typically use a forward declaration:
class MyClass; // <-- Forward declare MyClass.
int main(int argc, char *argv[])
{
MyClass m;
return 0;
}
class MyClass
{
};
In your case, the use of the class
keyword before the function parameter's type is essentially forward declaring the class name for you.
In this case
void recv(Client * c)
Compiler looks for declaration of Client
. If it cannot find, it will give error. You can solve it by forward declaration as shown following
class Client;
void recv(Client * c)
Although I have never seen second case, but it looks like that is also declaring class Client here.
Using keyword class, struct, enum in a type parameter declaration is called elaborated type specifier. It introduces the new type in the scope where the function is declared. It is similar to forward declaration.
There is also another using of such a declaration. For example if a name of an object or a function name hides a class or enum with the same name. For example
struct A {};
A A; // now A is seen as an identifier of the object
void f( struct A );