Class vs Object in C++ (Difference Between)
Classes v/s Objects in C++
You may say a class is a collection of objects and an object is a real-world entity, but I challenge most of them don’t understand its real meaning.
Here we will discuss what exactly we should understand about a class and object in OOPS and about Class vs Object in C++ .
Class
The design concept of class is similar to that of structures and unions
- Apt Definition of a class: A class is a logical entity where you can write logic (statements)
- No memory gets allocated for a class
Class Can be created as follows
class name_of_class{
// access specifiers
public:
// data members and member functions
int variable1;
void functioName1(){
// function definition here
}
} Example:
// name of the class
class Student
{
// access specifier
public:
// data members variables
int rollNo, weight, age;
string name;
// member functions
void displayDetails()
{
cout << "Roll No: " << rollNo << endl;
cout << "Name: " << name << endl;
}
};
In order to run the above code, we require some memory space so, that memory allocated for the elements in the class is nothing but an object Object
An object is a physical entity that represents memory for a class
- Definition of an object: The object is an instance of a class it holds the amount of memory required for the Logic present in the class
Hence you call an object an instance of a class or a real-world entity
int main(){
// declare Student object s1
Student s1;
// assigning values
s1.rollNo = 1;
s1.weight = 80;
s1.age = 21;
s1.name = "Peter";
// calling function for s1 object
s1.displayDetails();
return 0;
} Example
#include<iostream>
using namespace std;
// name of the class
class Student
{
// access specifier
public:
// data members variables
int rollNo, weight, age;
string name;
// member functions
void displayDetails()
{
cout << "Roll No: " << rollNo << endl;
cout << "Name: " << name << endl;
}
};
int main(){
// declare Student object s1
Student s1;
// assigning values
s1.rollNo = 1;
s1.weight = 80;
s1.age = 21;
s1.name = "Peter";
// calling function for s1 object
s1.displayDetails();
return 0;
}
Output
Roll No: 1 Name: Peter
Prime Course Trailer
Related Banners
Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription
Get over 200+ course One Subscription
Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Login/Signup to comment