Home >>C++ Tutorial >C++ Classes and Objects

C++ Classes and Objects

C++ Classes and Objects

Programs are basically designed by the help of the classes and objects in C++ because as the C++ is an object oriented language.

C++ Class

Class is basically a group of similar objects and is known as the template from which objects can be created and it may have methods, fields, etc.

Here are the examples of the object and the Class in C++:

class Employee    
 {    
     public:  
     int emp_id;  //field or data member     
     float emp_salary; //field or data member  
     String emap_name;//field or data member    
 }    

C++ Object

Objects in C++ are basically a real world entity that has a state and a behavior like rock, paper, scissors etc. In the previous statements the state represents the data and the behaviors represent the functionality.

Object is generally created at the runtime, as it is a runtime entity.

Each and every member of the class can be accessed by object and it is generally known as the instance of a class.

Here is an example of the object in C++

Employee emp;  //creating an object of employee 

C++ Class and Object Example

#include <iostream>  
using namespace std;  
class Employee 
{  
   public:  
      int emp_id;      
      string emp_name;      
};  
int main() 
{  
    Employee emp; //creating an object of Employee Class  
    emp.emp_id = 101;    
    emp.emp_name = "Anand";   
    cout<<emp.emp_id<<endl;  
    cout<<emp.emp_name<<endl;  
    return 0;  
}  
Output :
101
Anand

C++ Class and Objects another example

#include <iostream>  
using namespace std;  
class Employee 
{  
   public:  
       int emp_id;     
       string emp_name;      
       void save(int a, string b)    
        {    
            emp_id = a;    
            emp_name = b;    
        }    
       void show()    
        {    
            cout<<emp_id<<"  "<<emp_name<<endl;    
        }    
};  
int main(void) 
{  
    Employee emp1;   
    Employee emp2;  
    emp1.save(101, "Anand");    
    emp2.save(202, "Shipra");    
    emp1.show();    
    emp2.show();  
    return 0;  
}  
Output :
101 Anand
202 Shipra

No Sidebar ads