Create a class called Employee that includes three pieces of information as data members - C++ Class

C++ examples for Class:Class Creation

Introduction

A first name (type string), a last name (type string) and a monthly salary (type int).

Demo Code

                  
                 /*from  w w  w  .  ja  v a 2s  .  c  o m*/
                  
#include <iostream>
#include <string>
                  
class Employee {
 private:
    std::string firstName;
    std::string lastName;
    int monthlySalary;
                  
 public:
    Employee(std::string, std::string, int);
                  
    // SETTERS
    void setFirstName(std::string);
    void setLastName(std::string);
    void setMonthlySalary(int);
                  
    // GETTERS
    std::string getFirstName();
    std::string getLastName();
    int getMonthlySalary();
    int calculateSalary(int);
                  
    void giveRaise(int);
                  
    void showEmployee();
};
                  
Employee::Employee(std::string fName, std::string lName, int mSalary) {
    setFirstName(fName);
    setLastName(lName);
    setMonthlySalary(mSalary);
}
                  
// SETTERS
void Employee::setFirstName(std::string fName) { firstName = fName; }
void Employee::setLastName(std::string lName) { lastName = lName; }
void Employee::setMonthlySalary(int mSalary) {
    monthlySalary = (mSalary > 0) ? mSalary : 0;
}
// GETTERS
std::string Employee::getFirstName() { return firstName; }
std::string Employee::getLastName() { return lastName; }
int Employee::getMonthlySalary() { return monthlySalary; }
int Employee::calculateSalary(int months) { return monthlySalary * months; }
void Employee::giveRaise(int percent) {
    monthlySalary += (monthlySalary / 100) * percent;
}
void Employee::showEmployee() {
    std::cout << "Name: " << getFirstName() << " " << getLastName();
    std::cout << "\nMonthly Salary: " << getMonthlySalary();
    std::cout << "\nYearly Salary: " << calculateSalary(12) << std::endl;
    std::cout << std::endl;
}
                  
                  
int main(int argc, const char *argv[]) {
    Employee emp1("Bob", "Bobson", 1200);
    Employee emp2("Sue", "Sueson", 2000);
                  
    emp1.showEmployee();
    emp2.showEmployee();
                  
    emp1.giveRaise(10);
    emp2.giveRaise(10);
                  
    emp1.showEmployee();
    emp2.showEmployee();
    return 0;
}

Related Tutorials