Because a constructor does not work that way in C++, constructors are called once the object is created (or has been created). That means, that the code in the body shall execute after object creation, merely for validation purposes or so.
In C++, you can initialize the object that way, so when he did,
ChessBoard::ChessBoard ()
: _whose_move( "white" )
{
}
He was initializing the field
at the time of object creation, rather
after that. And whose_move is basically a string, and once again, in C++ you can easily create the variables like,
string _whose_move = "white";
string _whose_move("white");
string _whose_move = new string("white");
That all depends on what you want to do, and how you want to write the program, try this code sample I wrote for you;
C++ Shell[
^], it writes out my name, the code is as following,
#include <iostream>
#include <string>
int main()
{
std::string name("Afzaal Ahmad Zeeshan");
std::string name2 = "Afzaal Ahmad Zeeshan";
std::string* nameRef = new std::string("Afzaal Ahmad Zeeshan");
std::cout << "Hello, " << name << " from the constructor-like!\n" << std::endl;
std::cout << "Hello, " << name2 << " from the variable!\n" << std::endl;
std::cout << "Hello, " << *nameRef << " from the pointer!\n" << std::endl;
}
In this we have three ways to write the variable, you can check for yourself. Now take this concept back to the C++ constructor, and add the blend of syntax support of C++, you can easily see which of these can be supported in that domain.
Now see this,
class person {
public:
std::string name;
person(std::string);
};
person::person(std::string n) : name(n) {
std::cout << "Person created with name " << n << "." << std::endl;
}
Try doing this,
person::person(std::string n) : name = n {
It starts to complain, and so on and so forth. So the thing is, you have to follow the C++ standards and the syntax, otherwise there are problems. Serious ones.
Final program for you to try out and test;
C++ Shell[
^]