Class Constructors

 

This is a special method. Called once an object of a class is created. In order to create a constructor use the same name as the class, followed by brackets ().

 

Example:

 

#include <iostream>

using namespace std;

class My_Class // The class
{
  public: // Access specifier
    My_Class() // Constructor
    {
      cout << "Demo Code";
    }
};

int main()
{
  My_Class myObj; // this will automatically call the constructor
  return 0;
}

 

output:

Demo Code

 

Note: Just like regular functions constructors can also take parameters which can be used for initialising values for attributes.

 

Note: Constructors can be defined outside the class however it has a different syntax.

 

Steps:

  1. Declare the constructor inside the class

  2. Define it outside of the class by mentioning the name of the class

  3. Use :: operator, followed by the name of the class

 

Example:

 

#include <iostream>

using namespace std;

class Phone
{ // The class
  public: // Access specifier
    string brand; // Attribute
    string model; // Attribute
    int year; // Attribute
    Phone(string a, string b, int c); // Constructor declaration
};

// Constructor definition outside the class
Phone::Phone(string a, string b, int c)
{
  brand = a;
  model = b;
  year = c;
}

int main() {
  // Create Phone objects and call the constructor with different values
  Phone PhoneObj1("Nokia", "008", 1899);
  Phone PhoneObj2("Samsung", "Galaxy", 1969);

  // Print values
  cout << PhoneObj1.brand << " " << PhoneObj1.model << " " << PhoneObj1.year << "\n";
  cout << PhoneObj2.brand << " " << PhoneObj2.model << " " << PhoneObj2.year << "\n";

return 0;

}

 

Output:

Nokia 008 1899
Samsung Galaxy 1969