example2_default_member_initializations.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
37
38
#include <iostream>
#include <string>

class Car {
private:
    std::string brand;
    std::string model;
    int year = 2023;  // Default member initializer
    double price;

public:
    // Constructor using initializer list and default member initializer
    Car(const std::string& b, const std::string& m, double p)
        : brand(b), model(m), price(p) {
        std::cout << "Car constructed" << std::endl;
    }

    // Constructor that overrides the default year
    Car(const std::string& b, const std::string& m, int y, double p)
        : brand(b), model(m), year(y), price(p) {
        std::cout << "Car constructed with specified year" << std::endl;
    }

    void display() const {
        std::cout << year << " " << brand << " " << model 
                  << " priced at $" << price << std::endl;
    }
};

int main() {
    Car car1("Toyota", "Corolla", 25000.0);
    car1.display();

    Car car2("Honda", "Civic", 2022, 23000.0);
    car2.display();

    return 0;
}
Back to initializer_lists