Skip to main content

ProwessApps

Learn · Practice · Excel

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

C++ Code Example — Structure Programs

ADVERTISEMENT

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

  1. Define a class Emp with private variables (name, id, bsal).
  2. Define public member functions input() and display().
  3. In main(), declare an array of objects: Emp e[5].
  4. Loop through the array, calling e[i].input() to read data.
  5. 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 class is very similar to a struct, but with a major difference: access control. By default, all variables in a class are private (hidden from the outside world).
  • To interact with private data, a class must provide public functions (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)
ADVERTISEMENT