📌 Constructor Examples in C++

 


🔹 What is a Constructor?

A constructor is a special member function that is automatically called when an object of a class is created.
🔹 It has the same name as the class.
🔹 It does not have a return type (not even void).
🔹 Used to initialize object properties.


📌 Example 1: Area of Rectangle using Constructor

🚀 Approach

  1. Define a class Rectangle with attributes length and width.
  2. Use a constructor to initialize values when an object is created.
  3. Calculate the area.

🔹 C++ Code

#include <iostream>
using namespace std;

class Rectangle {
private:
    float length, width;

public:
    // Constructor to initialize values
    Rectangle(float l, float w) {
        length = l;
        width = w;
    }

    // Function to calculate area
    float area() {
        return length * width;
    }
};

int main() {
    Rectangle rect(5.0, 4.0); // Object created with values

    cout << "Area of Rectangle: " << rect.area() << endl;
    return 0;
}

🔹 Output

Area of Rectangle: 20

📌 Example 2: Constructor Overloading in C++

🚀 Approach

  1. Define multiple constructors with different parameters.
  2. Create objects using different constructors.

🔹 C++ Code

#include <iostream>
using namespace std;

class Box {
private:
    float length, width, height;

public:
    // Default Constructor
    Box() {
        length = width = height = 1.0;
    }

    // Parameterized Constructor
    Box(float l, float w, float h) {
        length = l;
        width = w;
        height = h;
    }

    // Function to calculate volume
    float volume() {
        return length * width * height;
    }
};

int main() {
    Box box1;              // Calls default constructor
    Box box2(5.0, 4.0, 3.0); // Calls parameterized constructor

    cout << "Default Box Volume: " << box1.volume() << endl;
    cout << "Custom Box Volume: " << box2.volume() << endl;
    return 0;
}

🔹 Output

Default Box Volume: 1
Custom Box Volume: 60

📌 Example 3: Constructor Invoking Example

🚀 Approach

  1. Define a constructor with a message to show invocation.
  2. Create an object to trigger constructor call.

🔹 C++ Code

#include <iostream>
using namespace std;

class Demo {
public:
    // Constructor
    Demo() {
        cout << "Constructor Invoked!" << endl;
    }
};

int main() {
    Demo obj1;  // Constructor is automatically called
    return 0;
}

🔹 Output

Constructor Invoked!

📌 Example 4: Constructor Deep Copy in C++

🚀 Approach

  1. Use a copy constructor for deep copying.
  2. Allocate memory dynamically.

🔹 C++ Code

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

class Student {
private:
    char* name;

public:
    // Constructor
    Student(const char* n) {
        name = new char[strlen(n) + 1]; // Allocate memory
        strcpy(name, n);
    }

    // Deep Copy Constructor
    Student(const Student &s) {
        name = new char[strlen(s.name) + 1];
        strcpy(name, s.name);
    }

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

    ~Student() { delete[] name; }
};

int main() {
    Student s1("Alice");
    Student s2 = s1; // Calls copy constructor

    s1.display();
    s2.display();
    return 0;
}

🔹 Output

Name: Alice
Name: Alice

📌 Example 5: Basic Copy Constructor Example

🚀 Approach

  1. Define a class Car with a copy constructor.
  2. Create an object and copy it.

🔹 C++ Code

#include <iostream>
using namespace std;

class Car {
public:
    string brand;

    // Constructor
    Car(string b) {
        brand = b;
    }

    // Copy Constructor
    Car(const Car &c) {
        brand = c.brand;
    }

    void show() {
        cout << "Car Brand: " << brand << endl;
    }
};

int main() {
    Car car1("Tesla");
    Car car2 = car1; // Calls copy constructor

    car1.show();
    car2.show();
    return 0;
}

🔹 Output

Car Brand: Tesla
Car Brand: Tesla

📌 Example 6: Copy Constructor (Shallow Copy)

🚀 Approach

  1. A shallow copy only copies pointer values, not actual data.
  2. Changing one object affects the other.

🔹 C++ Code

#include <iostream>
using namespace std;

class Student {
public:
    int* age;

    // Constructor
    Student(int a) {
        age = new int(a);
    }

    // Shallow Copy Constructor
    Student(const Student &s) {
        age = s.age;
    }

    void show() {
        cout << "Age: " << *age << endl;
    }
};

int main() {
    Student s1(20);
    Student s2 = s1; // Shallow copy

    s1.show();
    s2.show();

    // Changing s1 will affect s2
    *(s1.age) = 25;
    s1.show();
    s2.show();
    return 0;
}

🔹 Output

Age: 20
Age: 20
Age: 25
Age: 25

🔹 Problem: Both s1 and s2 share the same memory. Changing one affects the other.


📌 Example 7: Parameterized Constructor

🚀 Approach

  1. Define a class Employee with a parameterized constructor.
  2. Initialize values using a constructor.

🔹 C++ Code

#include <iostream>
using namespace std;

class Employee {
private:
    string name;
    int salary;

public:
    // Parameterized Constructor
    Employee(string n, int s) {
        name = n;
        salary = s;
    }

    void display() {
        cout << "Employee: " << name << ", Salary: " << salary << endl;
    }
};

int main() {
    Employee e1("John", 50000);
    Employee e2("Alice", 60000);

    e1.display();
    e2.display();
    return 0;
}

🔹 Output

Employee: John, Salary: 50000
Employee: Alice, Salary: 60000

📌 Summary

Example Description
Area of Rectangle using Constructor Initializes rectangle dimensions in constructor.
Constructor Overloading Multiple constructors with different parameters.
Constructor Invoking Example Demonstrates when constructors are called.
Constructor Deep Copy Allocates new memory to prevent shared pointer issues.
Copy Constructor Basic Example Copies object properties correctly.
Copy Constructor Shallow Copy Shares memory, causing unintended modifications.
Parameterized Constructor Initializes object attributes using parameters.

🚀 Need more examples? Let me know! 🚀

Post a Comment

0 Comments