What does a colon following a C++ constructor name do?
This is a member initializer list, and is part of the constructor's implementation.
The constructor's signature is:
MyClass();
This means that the constructor can be called with no parameters. This makes it a default constructor, i.e., one which will be called by default when you write MyClass someObject;
.
The part : m_classID(-1), m_userdata(0)
is called member initializer list. It is a way to initialize some fields of your object (all of them, if you want) with values of your choice.
After executing the member initializer list, the constructor body (which happens to be empty in your example) is executed. Inside it you could do more assignments, but once you have entered it all the fields have already been initialized - either to random, unspecified values, or to the ones you chose in your initialization list. This means the assignments you do in the constructor body will not be initializations, but changes of values.
C++, What does the colon after a constructor mean?
As others have said, it's an initialisation list. You can use it for two things:
- Calling base class constructors
- Initialising member variables before the body of the constructor executes.
For case #1, I assume you understand inheritance (if that's not the case, let me know in the comments). So you are simply calling the constructor of your base class.
For case #2, the question may be asked: "Why not just initialise it in the body of the constructor?" The importance of the initialisation lists is particularly evident for const
members. For instance, take a look at this situation, where I want to initialise m_val
based on the constructor parameter:
class Demo
{
Demo(int& val)
{
m_val = val;
}
private:
const int& m_val;
};
By the C++ specification, this is illegal. We cannot change the value of a const
variable in the constructor, because it is marked as const. So you can use the initialisation list:
class Demo
{
Demo(int& val) : m_val(val)
{
}
private:
const int& m_val;
};
That is the only time that you can change a const member variable. And as Michael noted in the comments section, it is also the only way to initialise a reference that is a class member.
Outside of using it to initialise const
member variables, it seems to have been generally accepted as "the way" of initialising variables, so it's clear to other programmers reading your code.
What is this colon in a constructor definition called?
That isn't a method definition, it's a constructor definition; the colon is used to specify the superclass constructor call which must be called prior to the subclass's constructor.
In Java, the super
keyword is used but it must be the first operation in a subclass constructor, whereas C# uses a syntax closer to C++'s initializer lists.
If a subclass' superclass' constructor does not have any parameters then an explicit call to the parent constructor is not necessary, it is only when arguments are required or if you want to call a specific overloaded constructor must you use this syntax.
Java:
public class Derived extends Parent {
public Derived(String x) {
super(x);
}
}
C#:
public class Derived : Parent {
public Derived(String x) : base(x) {
}
}
Update
The C# Language Specification 5.0 - https://msdn.microsoft.com/en-us/library/ms228593.aspx?f=255&MSPPError=-2147217396 has an explanation in section 10.11.1 "Constructor initializers"
All instance constructors (except those for class
Object
) implicitly include an invocation of another instance constructor immediately before the constructor-body. The constructor to implicitly invoke is determined by the constructor-initializer:
So the offiical technical term for this syntax...
: base(x, y, z)
...is "constructor-initializer", however the specification does not specifically call out the colon syntax and give it its own name. This author assumes the specification does not concern itself with such trivialities.
Use of colon in C# constructor header
You can always make a call to one constructor from within another. Say, for example:
public class mySampleClass
{
public mySampleClass(): this(10)
{
// This is the no parameter constructor method.
// First Constructor
}
public mySampleClass(int Age)
{
// This is the constructor with one parameter.
// Second Constructor
}
}
this
refers to same class, so when we say this(10)
, we actually mean execute the public mySampleClass(int Age)
method. The above way of calling the method is called initializer. We can have at the most one initializer in this way in the method.
In your case it going to call default constructor without any parameter
Colon after Constructor in dart
The part after :
is called "initializer list. It is a ,
-separated list of expressions that can access constructor parameters and can assign to instance fields, even final
instance fields. This is handy to initialize final fields with calculated values.
The initializer list is also used to call other constructors like : ..., super('foo')
.
Since about Dart version 1.24 the initializer list also supports assert(...)
which is handy to check parameter values.
The initializer list can't read from this
because the super constructors need to be completed before access to this
is valid, but it can assign to this.xxx
.
Pointing out as mentioned in the comments by user693336:
This also means the initializer list is executed before the constructor body. Also the initializer lists of all superclasses are executed before any of the constructor bodies are executed.
Example (copied from https://github.com/dart-lang/language/issues/1394):
class C {
final int x;
final int y;
C(this.x) : y = x + 1;
}
What is this weird colon-member ( : ) syntax in the constructor?
It's a member initialization list. You should find information about it in any good C++ book.
You should, in most cases, initialize all member objects in the member initialization list (however, do note the exceptions listed at the end of the FAQ entry).
The takeaway point from the FAQ entry is that,
All other things being equal, your code will run faster if you use initialization lists rather than assignment.
Variables after the colon in a constructor
It's a way of invoking the constructors of members of the point3 class. if x,y, and z are floats, then this is just a more efficient way of writing this
point3( float X, float Y, float Z):
{
x = X;
y = Y;
z = Z;
}
But if x, y & z are classes, then this is the only way to pass parameters into their constructors
In C# what category does the colon : fall into, and what does it really mean?
Colons are used in a dozen fundamentally different places (that I can think of, with the help of everyone in the comments):
Separating a class name from its base class / interface implementations in class definitions
public class Foo : Bar { }
Specifying a generic type constraint on a generic class or method
public class Foo<T> where T : Bar { }
public void Foo<T>() where T : Bar { }Indicating how to call another constructor on the current class or a base class's constructor prior to the current constructor
public Foo() : base() { }
public Foo(int bar) : this() { }Specifying the global namespace (as C. Lang points out, this is the namespace alias qualifier)
global::System.Console
Specifying attribute targets
[assembly: AssemblyVersion("1.0.0.0")]
Specifying parameter names
Console.WriteLine(value: "Foo");
As part of a ternary expression
var result = foo ? bar : baz;
As part of a
case
orgoto
labelswitch(foo) { case bar: break; }
goto Bar;
Foo: return true;
Bar: return false;Since C# 6, for formatting in interpolated strings
Console.WriteLine($"{DateTime.Now:yyyyMMdd}");
Since C# 7, in tuple element names
var foo = (bar: "a", baz: "b");
Console.WriteLine(foo.bar);
In all these cases, the colon is not used as an operator or a keyword (with the exception of ::
). It falls into the category of simple syntactic symbols, like []
or {}
. They are just there to let the compiler know exactly what the other symbols around them mean.
Colon in the method
For constructors (function names with the same name as the class name), the : indicates that a constructor of the base class will be called and will execute first, with any passed parameters, before the code of the child constructor.
So for the function public Cylinder(double radius, double height) : base(radius)
the constructor for Circle is executed before the code in the Cylinder constructor, which in turn calls the constructor for Shape setting this.x
and this.y
, and then executes its own code, which it has none, and then finally the code in Cylinder constructor is executed, setting y
.
: Colon in a Struct constructor
vertex
is the struct name, so vertex(string s)
is a constructor with a string
parameter. In a constructor, :
begins the member initialization list, which initializes member values and calls member constructors. The following brackets are the actual constructor body, which in this case is empty.
See Constructors and member initializer lists for more details.
Related Topics
C++ Alignment When Printing Cout ≪≪
Std::Thread Pass by Reference Calls Copy Constructor
How to Convert String to Char Array in C++
When Should I Use _Mm_Sfence _Mm_Lfence and _Mm_Mfence
Arrays VS Vectors: Introductory Similarities and Differences
Different Floating Point Result With Optimization Enabled - Compiler Bug
_Builtin_Prefetch, How Much Does It Read
How to Get the Error Message from the Error Code Returned by Getlasterror()
Deleting a Pointer to Const (T Const*)
How to Call a Function on All Variadic Template Args
Strict Aliasing Rule and 'Char *' Pointers
Sfinae to Check For Inherited Member Functions
Using Unicode in C++ Source Code
What Is the Logic Behind the "Using" Keyword in C++