Just a little bit about why you might need that syntax.
Consider this example, which definitely might occur in the real world:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
|
#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <string>
#include <ctime>
using namespace std;
class Shape
{
public:
Shape(int nVertices) { m_nVertices = nVertices; }
protected:
int m_nVertices;
};
class Square : public Shape
{
public:
Square(int nWidth)
{
m_nWidth = nWidth;
m_nVertices = 4;
}
protected:
int m_nWidth;
};
int main()
{
Square b(5);
return 0;
}
|
Try to compile it. It won't work because Shape has no constructors that take 0 parameters. But we aren't instantiating a shape anywhere! We are creating a square, and passing in a size to that constructor (which it requires). But even so, Square still has to construct itself as a Shape, so it (by default) calls its parent class's constructors with no parameters.
1 2 3
|
Square(int nWidth)
{ // <-------- Here, Square implicitly calls 'Shape::Shape()'
m_nWidth = nWidth;
|
How to fix? We tell Square to use a different constructor, using an initializer list
1 2 3 4
|
Square(int nWidth) : Shape(4)
{
m_nWidth = nWidth;
}
|
And now it compiles and works as expected. The same thing would apply if we had another class "House", which maybe uses a square to define where it is:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
|
class House
{
public:
House()
{
}
void SetBoundingSquare(const Square & bs)
{
m_BoundingSquare = bs;
}
protected:
Square m_BoundingSquare;
};
|
If you add this to the code, again, an error, that there is no default constructor for Square to construct m_BoundingSquare. This is because each data member of the class House has to be constructed, which occurs at about the same place parent constructor(s) are called. So the compiler is implicitly calling Square::Square() to construct m_BoundingSquare, which unfortunately doesn't exist! The solution is to add m_BoundingSquare into the initializer list with an appropriate value:
1 2 3 4
|
House() : m_BoundingSquare(5)
{
}
|
And all is right in the world again :)