< Previous | Contents | Next >
I declare a constructor in Critter with the following code:
Critter(int hunger = 0); // constructor prototype
As you can see from the declaration, the constructor has no return type. It can’t— it’s illegal to specify a return type for a constructor. Also, you have no flexibility when naming a constructor. You have to give it the same name as the class itself.
Hi n t
A default constructor requires no arguments. If you don’t define a default constructor, the compiler defines a minimal one for you that simply calls the default constructors of any data members of the class. If you write your own constructor, then the compiler won’t provide a default constructor for you. It’s usually a good idea to have a default constructor, so you should make sure to supply your own when necessary. One way to accomplish this is to supply default arguments for all parameters in a constructor definition.
I define the constructor outside of the class with the following code:
Critter::Critter(int hunger) // constructor definition
{
cout << "A new critter has been born!" << endl; m_Hunger = hunger;
}
The constructor displays a message saying that a new critter has been born and initializes the object’s m_Hunger data member with the argument value passed to the constructor. If no value is passed, then the constructor uses the default argument value of 0.
Tric k
You can use member initializers as a shorthand way to assign values to data members in a constructor. To write a member initializer, start with a colon after the constructor’s parameter list. Then type the name of the data member you want to initialize, followed by the expression you want to assign to the data member, surrounded by parentheses. If you have multiple initializers, separate them with commas. This is much simpler than it sounds (and it’s really useful, too). Here’s an example that assigns hunger to m_Hunger and boredom to m_Boredom. Member initializers are especially useful when you have many data members to initialize.
Critter::Critter(int hunger = 0, int boredom = 0): m_Hunger(hunger),
m_Boredom(boredom)
{} // empty constructor body