C++ Constructors

🚀 C++ Constructors – Start Things Right Automatically

In C++, a constructor is a special function that runs automatically when you create an object. It helps you set up the object with initial values—like a welcome kit when a new employee joins. 🎁

🎯 Why Use a Constructor?

  • It runs by itself when the object is created
  • It helps you avoid repeating setup code
  • Every class can have its own constructor

🔧 Example: Simple Constructor

#include <iostream>
using namespace std;

class Book {
public:
    string title;

    // Constructor
    Book() {
        title = "C++ Made Easy";
        cout << "Constructor called! Book title set." << endl;
    }

    void showTitle() {
        cout << "Book Title: " << title << endl;
    }
};

int main() {
    Book myBook;  // Constructor is called here
    myBook.showTitle();

    return 0;
}
  

Try It Now

⚙️ Types of Constructors

  • Default Constructor – No parameters
  • Parameterized Constructor – Takes values to initialize members
  • Copy Constructor – Makes a copy of another object

💡 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 showInfo() {
        cout << name << " is " << age << " years old." << endl;
    }
};

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

    s1.showInfo();
    s2.showInfo();

    return 0;
}
  

Try It Now

🧠 Summary

  • Constructors set things up automatically when objects are made
  • Great for initializing values
  • You can create multiple types: default, parameterized, and copy constructors

With constructors, your objects now come pre-loaded and ready to go! Let’s keep building your C++ skills. 🛠️