Functions and Objects
Constructor in C++
A constructor is a special method that builds the instance of an object when a new object is created.
Syntax
//within a class
public:
className {
//set fields and call methods
}
Notes
There can be multiple constructors with a different number or types of input parameters. This is known as overloading (in fact, methods can be overloaded as well). This is useful if there are many fields within the class, and the user wants defaults set for these fields if not passed in during instantiation.
Often times, a constructor's input parameters will have the same variable name as the variables within the class. Member variables within the class can be referenced using the 'this' keyword.
Example
using namespace std;
class City {
public:
string cityName; //fields
int population;
City() { //constructor if no input parameters are provided
this->cityName = "No city name provided";
this->population = 0;
}
City(String cityName) { //constructor if only a city name is provided
this->cityName = cityName; //this keyword distinguishes the cityName's
this->population = 0;
}
City(String cityName, int population) { //constructor if both parameters provided
this->cityName = cityName;
this->population = population;
}
}