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.
- class Student
- {
- public:
- int id; //field or data member
- float salary; //field or data member
- String name;//field or data member
- }
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.
- Student s1; //creating an object of Student
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.- #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;
- }
201 Sonoo Jaiswal
No comments:
Post a Comment
Please write your view and suggestion....