Geek Slack

Learn C++
About Lesson


C++ Constructors


C++ Constructors

1. Default Constructor

Example of default constructor:

#include <iostream>
#include <string>

// Class declaration
class Person {
private:
    std::string name;
    int age;

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

    // Member function to set name and age
    void setData(std::string n, int a) {
        name = n;
        age = a;
    }

    // Member function to display person's info
    void displayInfo() {
        std::cout << "Name: " << name << ", Age: " << age << std::endl;
    }
};

int main() {
    // Create object of class Person using default constructor
    Person person1;

    // Display default info
    std::cout << "Default Person:" << std::endl;
    person1.displayInfo();

    // Set data using member function
    person1.setData("Alice", 30);

    // Display updated info
    std::cout << "Updated Person:" << std::endl;
    person1.displayInfo();

    return 0;
}

2. Parameterized Constructor

Example of parameterized constructor:

#include <iostream>
#include <string>

// Class declaration
class Car {
private:
    std::string brand;
    int year;

public:
    // Parameterized constructor
    Car(std::string b, int y) {
        brand = b;
        year = y;
    }

    // Member function to display car's info
    void displayInfo() {
        std::cout << "Brand: " << brand << ", Year: " << year << std::endl;
    }
};

int main() {
    // Create object of class Car using parameterized constructor
    Car car1("Toyota", 2020);

    // Display car's info
    car1.displayInfo();

    return 0;
}

3. Constructor Overloading

Example of constructor overloading:

#include <iostream>
#include <string>

// Class declaration
class Rectangle {
private:
    double length;
    double width;

public:
    // Default constructor
    Rectangle() {
        length = 0.0;
        width = 0.0;
    }

    // Parameterized constructor
    Rectangle(double l, double w) {
        length = l;
        width = w;
    }

    // Member function to calculate area
    double calculateArea() {
        return length * width;
    }
};

int main() {
    // Create objects of class Rectangle using different constructors
    Rectangle rect1; // Default constructor
    Rectangle rect2(5.0, 3.0); // Parameterized constructor

    // Calculate and display area
    std::cout << "Area of rectangle 1: " << rect1.calculateArea() << std::endl;
    std::cout << "Area of rectangle 2: " << rect2.calculateArea() << std::endl;

    return 0;
}

Conclusion

Constructors in C++ are special member functions that are automatically called when objects of a class are created. This chapter covered default constructors, parameterized constructors, and constructor overloading. Understanding constructors allows you to initialize object data and manage object creation effectively in C++ programs.

Join the conversation