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?
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.
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.
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.
The constructor() method is a special method for creating and initializing objects created within a class.
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:
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
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With