Game Development Reference
In-Depth Information
Constructors and Destructors
When you use the class keyword, you are actually informing the compiler to create a new type in the
C++ language. When you create a variable of a given type in C++ the first task to be completed is
generally initialization. C++ provides methods called constructors that are called when our classes
are initialized. Listing 8-5 adds a constructor to our Player class.
Listing 8-5. The Player Class Constructor
class Player
{
private:
std::string m_name;
public:
Player(const std::string& name)
: m_name(name)
{
}
void SetName(const std::string& name)
{
m_name = name;
}
const std::string& GetName() const
{
return m_name;
}
};
The bold code in Listing 8-5 shows the class constructor. The constructor is a special method in C++
classes. It does not contain a return type as it can never return a value and it also contains an initializer
list. The initializer list is used to call the constructors on our member variables and Listing 8-5 shows
that we have called the string class constructor on m_name before the constructor function itself is
executed. We would use a comma if we had more variables to add to the initializer list:
Player(const std::string& name, int anotherVariable)
: m_name(name)
, m_anotherVariable(anotherVariable)
{
}
If you try to execute this code after adding this constructor you will see that there is another compile
error in the code.
Error 1 error C2512: 'Player' : no appropriate default constructor available
 
Search WWH ::




Custom Search