tags:

views:

92

answers:

3

So, I came across an interesting method signature that I don't quite understand, it went along the lines of:

void Initialize(std::vector< std::string > & param1, class SomeClassName * p);

what I don't understand is the "class" keyword being used as the parameter, why is it there? Is it necessary to specify or it is purely superficial?

+7  A: 

It is a forward declaration of the class. It is the effectively the same as

class SomeClassName;
void Initialize(std::vector< std::string > & param1, SomeClassName * p);

There are many situations in which a forward declaration is useful; there's a whole list of things that you can and can't do with a forward declaration in this answer to another question).

James McNellis
does it act as forward declaration then?
ra170
@ra170: Yes, it does.
James McNellis
"but you need to use a pointer or reference to an instance of the class" -> If you just have a non-definition function declaration like in this case, you can go fine with value-parameters, though.
Johannes Schaub - litb
@James - interesting, I have never seen a forward declaration inside a function parameter before.
Remy Lebeau - TeamB
@Remy: To tell the truth, I've _never_ seen this done before in real code either. @Johannes: Yeah; I posted the link to the list of what can and can't be done because I knew I'd forget something.
James McNellis
+1  A: 

It's not superficial. It allows you to specify "SomeClassName" as a parameter even if "SomeClassName" hasn't been defined yet.

Peter Ruderman
does it act as forward declaration then?
ra170
+1  A: 

Most superficial. In C, when you define a struct:

struct x { 
    int member;
    char member2;
};

To use that, you have to use struct x whatever. If you want to use x as a name by itself (without the struct preceding it) you have to use a typedef:

typedef struct x { 
    int member;
    char member2;
} x;

In C++, however, the first (without the typedef) has roughly the same effect as the second (both define x so you can use it by itself, without struct preceding it). In C++, a class is essentially the same as a struct, except that it defaults to private instead of public (for both members and inheritance).

The only place there's a difference is if there is no definition of the class in scope at the point of the function declaration.

Jerry Coffin