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 function signatures, then if I add the keyword "class" in front of the respective variables, it can always solve this kind of compile-time errors.
For example, if the compiler does not recognize the type Client in
void recv( Client * c )
then if I change it to
void recv( class Client * c )
the problem is solved.
I am sorry that I cannot come up with a concrete example as I randomly came up with this question.
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 );
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With