C++ Object and Class - Learn in the easy way

Happy Learning...

ads

Post Top Ad

C++ Object and Class

Share This

C++ Object and Class

Since C++ is an object-oriented language, the program is designed using objects and classes in C++.

C++ Object

In C++, Object is a real-world entity, for example, chair, car, pen, mobile, laptop etc.
In other words, an object is an entity that has state and behavior. Here, state means data and behavior mean functionality.
An object is a runtime entity, it is created at runtime.
An object is an instance of a class. All the members of the class can be accessed through an object.
Let's see an example to create an object of student class using s1 as the reference variable.
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++ Class

In C++, an 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 a C++ class that has three fields only.

class Student    
 {    
     public:    
  int id;  //field or data member         
 float salary; //field or data member     
  String name;//field or data member  
   } 


C++ Object and Class Example

Let's see an example of a class that has two fields: id and name. It creates an instance of the class, initializes the object and prints the object value.

#include <iostream>  
using namespace std;  
class Student {  
  public:  
 int id;//data member (also instance variable)      
string name;//data member(also instance variable)      
};  
int main() {  
  Student s1; //creating an object of Student   
 s1.id = 201;    
s1.name = "Sonoo Jaiswal";   
 cout<<s1.id<<endl;  
cout<<s1.name<<endl;  
return 0;  
}  
Output:
201
Sonoo Jaiswal

No comments:

Post a Comment

Tell me What can I do for you.....Comment, please

Post Bottom Ad

Pages