Thursday, 13 July 2017

C++ Class Object

C++ Class

In C++, object is a group of similar objects. It is a template from which objects are created. It can have fields, methods, constructors etc.
Let's see an example of C++ class that has three fields only.
  1. class Student    
  2.  {    
  3.      public:  
  4.      int id;  //field or data member     
  5.      float salary; //field or data member  
  6.      String name;//field or data member    
  7.  }    

C++ Object

In C++, Object is a real world entity, for example, chair, car, pen, mobile, laptop etc.
In other words, object is an entity that has state and behavior. Here, state means data and behavior means functionality.
Object is a runtime entity, it is created at runtime.
Object is an instance of a class. All the members of the class can be accessed through object.
Let's see an example to create object of student class using s1 as the reference variable.
  1. Student s1;  //creating an object of Student      
In this example, Student is the type and s1 is the reference variable that refers to the instance of Student class.

C++ Object and Class Example

Let's see an example of class that has two fields: id and name. It creates instance of the class, initializes the object and prints the object value.
  1. #include <iostream>  
  2. using namespace std;  
  3. class Student {  
  4.    public:  
  5.       int id;//data member (also instance variable)      
  6.       string name;//data member(also instance variable)      
  7. };  
  8. int main() {  
  9.     Student s1; //creating an object of Student   
  10.     s1.id = 201;    
  11.     s1.name = "Sonoo Jaiswal";   
  12.     cout<<s1.id<<endl;  
  13.     cout<<s1.name<<endl;  
  14.     return 0;  
  15. }  
Output:

201 Sonoo Jaiswal

No comments:

Post a Comment

Please write your view and suggestion....