example1_basic_usage.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
#include <iostream>
#include <string>

class Person {
private:
    std::string name;
    int age;
    const double height;

public:
    // Constructor using initializer list
    Person(const std::string& n, int a, double h)
        : name(n), age(a), height(h) {
        std::cout << "Person constructed" << std::endl;
    }

    void display() const {
        std::cout << name << " is " << age << " years old and " 
                  << height << "m tall." << std::endl;
    }
};

int main() {
    Person person("Alice", 30, 1.65);
    person.display();

    return 0;
}
Back to initializer_lists