example3_delegating_constructors.cpp

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include <iostream>
#include <string>

class Employee {
private:
    std::string name;
    int id;
    double salary;

public:
    // Primary constructor
    Employee(const std::string& n, int i, double s)
        : name(n), id(i), salary(s) {
        std::cout << "Primary constructor called" << std::endl;
    }

    // Delegating constructor
    Employee(const std::string& n, int i)
        : Employee(n, i, 50000.0) {  // Calls the primary constructor
        std::cout << "Delegating constructor called" << std::endl;
    }

    void display() const {
        std::cout << name << " (ID: " << id << ") earns $" << salary << std::endl;
    }
};

int main() {
    Employee emp1("Bob", 1001, 60000.0);
    emp1.display();

    Employee emp2("Alice", 1002);
    emp2.display();

    return 0;
}
Back to initializer_lists