C++ Constructors

C++ Constructors

A constructor in C++ is a special method that is automatically called when an object of a class is created.

It is generally used to initialize the object's attributes with default or starting values.

Rules for Constructors:

  1. The constructor must have exactly the same name as the class.
  2. It does not have a return type (not even void).
  3. It is always declared public (usually, though advanced patterns might use private constructors).

1. Creating a Basic Constructor

Basic Constructor Example

#include <iostream>
using namespace std;

class MyClass { public: // This is the constructor MyClass() { cout << "Object created! Constructor called.\n"; } };

int main() { MyClass myObj; // Constructor is called automatically here! return 0; }

Notice that we didn't explicitly call myObj.MyClass(). The constructor ran the exact moment MyClass myObj; was executed.


2. Constructor Parameters

Constructors can also take parameters, just like regular functions. This is incredibly useful for setting initial values for attributes right when the object is created.

Parameterized Constructor Example

#include <iostream>
#include <string>
using namespace std;

class Car { public: string brand; string model; int year; // Constructor with parameters Car(string x, string y, int z) { brand = x; model = y; year = z; } };

int main() { // Create objects and pass values to the constructor Car carObj1("BMW", "X5", 1999); Car carObj2("Ford", "Mustang", 1969);

// Print values cout << carObj1.brand << " " << carObj1.model << " " << carObj1.year << "\n"; cout << carObj2.brand << " " << carObj2.model << " " << carObj2.year << "\n"; return 0; }

This code is much cleaner than creating an object and then setting each attribute one by one on separate lines!


Exercise

?

Which of the following is TRUE about a constructor in C++?