Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declaring a variable with "class " keyword vs Declaring one without "class" keyword in function signatures

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.

like image 847
cpp_noname Avatar asked Feb 19 '14 12:02

cpp_noname


3 Answers

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 );
like image 154
Vlad from Moscow Avatar answered Nov 09 '22 13:11

Vlad from Moscow


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.

like image 30
doptimusprime Avatar answered Nov 09 '22 13:11

doptimusprime


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.

like image 36
Karl Nicoll Avatar answered Nov 09 '22 13:11

Karl Nicoll