Create a class to store the following information about an employee. Name, Emp. Id, Salary.
Store the information of 5 employee. Calculate Gross salary. Display all the information of all the employees in tabular form. Display the size of the class
Objective
Write a C++ program to manage Employee data using a Class instead of a Structure.
Algorithm / Approach
- Define a
class Empwith private variables (name, id, bsal). - Define
publicmember functionsinput()anddisplay(). - In
main(), declare an array of objects:Emp e[5]. - Loop through the array, calling
e[i].input()to read data. - Loop again, calling
e[i].display()to print the data and calculate Gross Salary (12 * bsal).
main.cpp
#include<iostream>
using namespace std;
class Emp {
string name;
int id,bsal;
public :
void input() {
cout<<"Enter Name ";
getline(cin,name);
cout<<"Enter Id ";
cin>>id;
cout<<"Enter Basic Salary ";
cin>>bsal;
cin.ignore(1,'\n');
}
void display() {
cout<< id<<"\t"<< name<<"\t";
cout<< bsal<<"\t"<< 12*bsal<< endl;
}
};
int main() {
Emp e[5];
for(int i = 0; i<5;i++) {
e[i].input();
}
for(int i = 0; i<5;i++ ) {
e[i].display();
}
return 0;
}
Expected Output
Enter Name Anup Enter id 12 Enter basic salary 22000 Enter Name Ashok Enter id 15 Enter basic salary 18000 Enter Name Ayan Enter id 51 Enter basic salary 50000 Enter Name XYZ Enter id 11 Enter basic salary 8000 Enter Name Vinay Enter id 23 Enter basic salary 15000 Anup 12 22000 264000 Ashok 15 18000 216000 Ayan 51 50000 600000 XYZ 11 8000 96000 Vinay 23 15000 180000
Explanation of the Program
- In C++, a
classis very similar to astruct, but with a major difference: access control. By default, all variables in a class areprivate(hidden from the outside world). - To interact with private data, a class must provide
publicfunctions (methods). This concept of hiding raw data and forcing the programmer to use specific functions is called Encapsulation.
Complexity
Time Complexity
O(n)
Space Complexity
O(n)