15

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?

ra170
  • 3,643
  • 7
  • 38
  • 52
  • I saw this as well in a class member declaration and I was going crazy trying to find out what it meant. `class Foo{ private: class Bar* pointerToBar; }` – Vicro Feb 26 '15 at 09:20

4 Answers4

16

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).

Community
  • 1
  • 1
James McNellis
  • 348,265
  • 75
  • 913
  • 977
  • does it act as forward declaration then? – ra170 May 14 '10 at 18:50
  • 1
    "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 May 14 '10 at 23:30
  • interesting, I have never seen a forward declaration inside a function parameter before. – Remy Lebeau May 15 '10 at 01:33
  • @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 May 15 '10 at 03:25
1

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

Peter Ruderman
  • 12,241
  • 1
  • 36
  • 58
1

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
  • 476,176
  • 80
  • 629
  • 1,111
0

it is the same as you write:

for(int i=0;i<10;i++) 

as

int i; 
for(i=0;i<10;i++)

the class declaration is a definition and a pointer to it

musefan
  • 47,875
  • 21
  • 135
  • 185
justCurious
  • 720
  • 7
  • 13