Add Value to Base Class Constructor Using Member Initializer List in C++

 


1️⃣ Why Use Member Initializer List in Inheritance?

When a derived class is created, it must initialize the base class constructor.
✅ Ensures proper initialization of base class members
✅ More efficient than assigning values in the constructor body
✅ Required for const and reference members


2️⃣ Syntax

class Base {
public:
    int x;
    Base(int a) : x(a) {}  // Base class constructor with initializer list
};

class Derived : public Base {
public:
    int y;
    Derived(int a, int b) : Base(a), y(b) {}  // Passing value to Base constructor
};

3️⃣ Example: Initializing Base Class Using Member Initializer List

#include <iostream>
using namespace std;

class Base {
protected:
    int baseValue;

public:
    // Base class constructor
    Base(int b) : baseValue(b) {
        cout << "Base Class Constructor: baseValue = " << baseValue << endl;
    }
};

class Derived : public Base {
private:
    int derivedValue;

public:
    // Using Member Initializer List to pass value to Base class
    Derived(int b, int d) : Base(b), derivedValue(d) {
        cout << "Derived Class Constructor: derivedValue = " << derivedValue << endl;
    }
};

int main() {
    Derived obj(10, 20);  // Passing values to Base and Derived class constructors

    return 0;
}

🔹 Output

Base Class Constructor: baseValue = 10
Derived Class Constructor: derivedValue = 20

4️⃣ Example: Initializing Multiple Members Including Base Class

#include <iostream>
using namespace std;

class Person {
protected:
    string name;
    int age;

public:
    Person(string n, int a) : name(n), age(a) {
        cout << "Person Constructor: Name = " << name << ", Age = " << age << endl;
    }
};

class Employee : public Person {
private:
    double salary;

public:
    // Passing values to Base class (Person) and initializing own members
    Employee(string n, int a, double s) : Person(n, a), salary(s) {
        cout << "Employee Constructor: Salary = $" << salary << endl;
    }
};

int main() {
    Employee emp("John", 30, 50000.0);

    return 0;
}

🔹 Output

Person Constructor: Name = John, Age = 30
Employee Constructor: Salary = $50000

5️⃣ Key Takeaways

✔ Base class must be initialized before the derived class.
✔ Use Member Initializer List to pass values efficiently.
✔ Ensures proper initialization of const and reference members.

Would you like an example with multiple inheritance and initializer lists? 🚀

Post a Comment

0 Comments