C++ Constructors

Introduction

Constructors are special member functions in C++ that are automatically called when an object of a class is created. They are used to initialize objects and can set initial values for the data members of the class. Understanding constructors is essential for properly managing the initialization of objects in C++.

Defining Constructors

Syntax for Defining a Constructor

A constructor has the same name as the class and no return type, not even void.

class ClassName {
public:
    // Constructor
    ClassName(parameters) {
        // Constructor body
    }
};

Example: Basic Constructor

#include <iostream>
using namespace std;

class Person {
public:
    string name;
    int age;

    // Constructor
    Person(string n, int a) {
        name = n;
        age = a;
    }

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

int main() {
    // Create an object using the constructor
    Person person1("Alice", 25);

    // Display the person's details
    person1.display();

    return 0;
}

Output

Name: Alice, Age: 25

Explanation

  • Person(string n, int a) is a constructor that initializes the name and age members.
  • Person person1("Alice", 25); creates an object person1 using the constructor.

Types of Constructors

Default Constructor

A default constructor is a constructor that takes no parameters. If no constructors are defined, the compiler provides a default constructor.

Example: Default Constructor

#include <iostream>
using namespace std;

class Person {
public:
    string name;
    int age;

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

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

int main() {
    // Create an object using the default constructor
    Person person1;

    // Display the person's details
    person1.display();

    return 0;
}

Output

Name: Unknown, Age: 0

Explanation

  • Person() is a default constructor that initializes the name and age members to default values.
  • Person person1; creates an object person1 using the default constructor.

Parameterized Constructor

A parameterized constructor is a constructor that takes one or more parameters to initialize the object with specific values.

Example: Parameterized Constructor

#include <iostream>
using namespace std;

class Person {
public:
    string name;
    int age;

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

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

int main() {
    // Create an object using the parameterized constructor
    Person person1("Bob", 30);

    // Display the person's details
    person1.display();

    return 0;
}

Output

Name: Bob, Age: 30

Explanation

  • Person(string n, int a) is a parameterized constructor that initializes the name and age members with specific values.
  • Person person1("Bob", 30); creates an object person1 using the parameterized constructor.

Copy Constructor

A copy constructor initializes an object using another object of the same class.

Example: Copy Constructor

#include <iostream>
using namespace std;

class Person {
public:
    string name;
    int age;

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

    // Copy constructor
    Person(const Person &p) {
        name = p.name;
        age = p.age;
    }

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

int main() {
    // Create an object using the parameterized constructor
    Person person1("Charlie", 35);

    // Create another object using the copy constructor
    Person person2 = person1;

    // Display the details of both persons
    person1.display();
    person2.display();

    return 0;
}

Output

Name: Charlie, Age: 35
Name: Charlie, Age: 35

Explanation

  • Person(const Person &p) is a copy constructor that initializes the name and age members using another object of the same class.
  • Person person2 = person1; creates an object person2 using the copy constructor.

Constructor Initialization Lists

Constructor initialization lists provide an efficient way to initialize class members. They can also initialize constant and reference members which cannot be assigned values inside the constructor body.

Example: Constructor Initialization List

#include <iostream>
using namespace std;

class Person {
public:
    string name;
    int age;

    // Constructor with initialization list
    Person(string n, int a) : name(n), age(a) {}

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

int main() {
    // Create an object using the constructor with initialization list
    Person person1("David", 40);

    // Display the person's details
    person1.display();

    return 0;
}

Output

Name: David, Age: 40

Explanation

  • Person(string n, int a) : name(n), age(a) {} is a constructor with an initialization list that initializes the name and age members.

Destructor

A destructor is a special member function that is automatically called when an object goes out of scope or is explicitly deleted. It is used to release resources allocated to the object.

Syntax for Defining a Destructor

A destructor has the same name as the class preceded by a tilde (~) and no parameters.

class ClassName {
public:
    // Destructor
    ~ClassName() {
        // Destructor body
    }
};

Example: Destructor

#include <iostream>
using namespace std;

class Person {
public:
    string name;
    int age;

    // Constructor
    Person(string n, int a) {
        name = n;
        age = a;
    }

    // Destructor
    ~Person() {
        cout << "Destructor called for " << name << endl;
    }

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

int main() {
    // Create an object using the constructor
    Person person1("Eve", 28);

    // Display the person's details
    person1.display();

    return 0;
}

Output

Name: Eve, Age: 28
Destructor called for Eve

Explanation

  • ~Person() is a destructor that prints a message when called.
  • The destructor is automatically called when person1 goes out of scope.

Example Programs

Example 1: BankAccount Class with Constructors and Destructor

#include <iostream>
using namespace std;

class BankAccount {
private:
    string accountHolder;
    double balance;

public:
    // Default constructor
    BankAccount() : accountHolder("Unknown"), balance(0.0) {}

    // Parameterized constructor
    BankAccount(string name, double initialBalance) : accountHolder(name), balance(initialBalance) {}

    // Copy constructor
    BankAccount(const BankAccount &account) : accountHolder(account.accountHolder), balance(account.balance) {}

    // Destructor
    ~BankAccount() {
        cout << "Destructor called for " << accountHolder << endl;
    }

    void display() {
        cout << "Account Holder: " << accountHolder << ", Balance: $" << balance << endl;
    }
};

int main() {
    // Create objects using different constructors
    BankAccount account1;
    BankAccount account2("John Doe", 1000.0);
    BankAccount account3 = account2;

    // Display account details
    account1.display();
    account2.display();
    account3.display();

    return 0;
}

Output

Account Holder: Unknown, Balance: $0
Account Holder: John Doe, Balance: $1000
Account Holder: John Doe, Balance: $1000
Destructor called for Unknown
Destructor called for John Doe
Destructor called for John Doe

Explanation

  • The BankAccount class has a default constructor, a parameterized constructor, and a copy constructor.
  • The destructor prints a message when an object is destroyed.
  • The program creates objects using different constructors and displays their details.

Example 2: Student Class with Constructor Initialization List

#include <iostream>
using namespace std;

class Student {
private:
    string name;
    int rollNumber;
    double marks;

public:
    // Constructor with initialization list
    Student(string n, int r, double m) : name(n), rollNumber(r), marks(m) {}

    void display() {
        cout << "Name: " << name << ", Roll Number: " << rollNumber << ", Marks: " << marks << endl;
    }
};

int main() {
    // Create a Student object
    Student student1("Alice", 101, 95.5);

    // Display student

 details
    student1.display();

    return 0;
}

Output

Name: Alice, Roll Number: 101, Marks: 95.5

Explanation

  • The Student class has a constructor with an initialization list that initializes name, rollNumber, and marks.
  • The student1 object is created and its details are displayed.

Conclusion

Constructors in C++ are special member functions that initialize objects when they are created. This chapter covered different types of constructors, including default constructors, parameterized constructors, copy constructors, and constructor initialization lists. It also explained destructors, which are used to release resources when an object is destroyed. Example programs demonstrated the practical use of constructors and destructors in C++. Understanding how to use constructors and destructors effectively is crucial for managing object initialization and cleanup in C++.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top