Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 831
Andreas Avatar asked Oct 10 '12 14:10

Andreas


People also ask

What is a class in constructor?

A constructor of a class is a special method that gets called when a class is instantiated using the NEW function. A constructor for a class has the same name as the class name. Unlike ordinary methods, a constructor definition is identified by the CONSTRUCTOR statement.

What is class constructor and object?

In class-based, object-oriented programming, a constructor (abbreviation: ctor) is a special type of subroutine called to create an object. It prepares the new object for use, often accepting arguments that the constructor uses to set required member variables.

What is class and explain?

The class is one of the defining ideas of object-oriented programming. Among the important ideas about classes are: A class can have subclasses that can inherit all or some of the characteristics of the class. In relation to each subclass, the class becomes the superclass.

What is class constructor function?

The constructor() method is a special method for creating and initializing objects created within a class.


1 Answers

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
};
like image 181
Luchian Grigore Avatar answered Sep 25 '22 02:09

Luchian Grigore