example3_getter_setter.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
39
40
41
42
43
44
45
46
47
#include <iostream>
#include <string>

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

public:
    Employee(const std::string& n, int a, double s) 
        : name(n), age(a), salary(s) {}

    // Getter methods
    std::string getName() const { return name; }
    int getAge() const { return age; }
    double getSalary() const { return salary; }

    // Setter methods
    void setName(const std::string& n) { name = n; }
    void setAge(int a) { 
        if (a > 0 && a < 120) age = a; 
        else std::cout << "Invalid age" << std::endl;
    }
    void setSalary(double s) { 
        if (s >= 0) salary = s; 
        else std::cout << "Invalid salary" << std::endl;
    }

    void displayInfo() const {
        std::cout << "Name: " << name << ", Age: " << age 
                  << ", Salary: $" << salary << std::endl;
    }
};

int main() {
    Employee emp("Alice", 30, 50000);
    emp.displayInfo();

    emp.setAge(31);
    emp.setSalary(55000);
    emp.displayInfo();

    emp.setAge(-5); // This will print an error message

    return 0;
}
Back to encapsulation