C++ Constructors

A constructor in C++ is a special member function of a class that is automatically called when an object of the class is created. Constructors are used to initialize objects and set default values for their attributes. They have the same name as the class and do not have a return type, not even void.

Types of Constructors

  • Default Constructor: A constructor with no parameters.
  • Parameterized Constructor: A constructor that takes parameters to initialize attributes with specific values.
  • Copy Constructor: A constructor that creates a new object as a copy of an existing object.

Example: Default Constructor

#include <iostream>
using namespace std;

class Student {
public:
    string name;
    int age;

    // Default constructor
    Student() {
        name = "Unknown";
        age = 0;
    }

    void display() {
        cout << "Name: " << name << ", Age: " << age << endl;
    }
};

int main() {

    Student s1; // Default constructor is called automatically
    s1.display();

    return 0;
}

Output

Name: Unknown, Age: 0

Example: Parameterized Constructor

#include <iostream>
using namespace std;

class Student {
public:
    string name;
    int age;

    // Parameterized constructor
    Student(string n, int a) {
        name = n;
        age = a;
    }

    void display() {
        cout << "Name: " << name << ", Age: " << age << endl;
    }
};

int main() {

    Student s1("Alice", 20);
    Student s2("Bob", 22);

    s1.display();
    s2.display();

    return 0;
}

Output

Name: Alice, Age: 20
Name: Bob, Age: 22

Important Notes

  • Constructors have the same name as the class and no return type.
  • If no constructor is defined, the compiler provides a default constructor automatically.
  • Parameterized constructors allow initializing objects with specific values at the time of creation.

Next Topic

Next, learn about Destructors in C++.