Andreas
Andreas

Reputation: 7550

What does "class" mean in a constructor?

I saw this constructor:

MyClass(class MyOtherClass* = 0) {}

What does the class keyword mean? Does the constructor take a MyOtherClass pointer and defaults the argument to the null pointer?

Upvotes: 5

Views: 166

Answers (1)

Luchian Grigore
Luchian Grigore

Reputation: 258618

It's a forward declaration. MyOtherClass doesn't have to be defined before use in this context, so a forward declaration is enough. The =0 is the default value for the argument.

Braindump of the cases where you don't need a full definition:

  • member pointers
  • member references
  • method parameter types
  • method return types

Compare the following:

//MyClass.h
class MyClass
{
    MyClass(MyOtherClass* = 0) {} //doesn't compile
                                  //doesn't know what MyOtherClass is
};

//MyClass.h
class MyClass
{
    MyClass(class MyOtherClass* = 0) {} //compiles, MyOtherClass is declared
};

//MyClass.h
class MyOtherClass;   //declare MyOtherClass
class MyClass
{
    MyClass(MyOtherClass* = 0) {} //compiles, declaration available
};

Upvotes: 10

Related Questions