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.

//within a class
    className {
        //set fields and call methods


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.

using namespace std;

class City {
    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;

See Also

Classes - C++ Tutorial

Add to Slack

< Class Declaration & Structure   |   Instantiation >

© 2019 SyntaxDB. All Rights Reserved.