Class v/s Object in C++

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 it’s real meaning.
Here we will discuss what exactly we should understand about a class and object in OOPS

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 logics (statements)
  • No memory gets allocated for a class

Generally class represent any of these 5 elements

class <class_name>
{
Variables;
Methods;
Constructors/ destructors;
Instance block;
Static block;
}
Class and Object in C++

Example:

class trish 
{ 
public: 
int a=2; 
int b=3; 
void add() //logics
{ 
cout<<"sum is "<<a+b<<"\n"; 
} //NO MEMORY ALLOCTED AS OF NOW
};

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 which represents memory for a class

  • Apt definition of an object: The object holds the amount of memory required for the Logics present in the class
  • Hence you call object an instance of a class or a real-world entity

Example

main()
{
trish t;
cout<<sizeof(t)<<"bytes\n"<<endl;//object size 
t.add();
}

O/P

8 bytes
sum is 5

Here t1 is an object of the class trish if you display size of this object t1 you  will get the sum of sizes of individual members (int a +int b= 4 +4 =8) bytes

Disadvantages of procedural programming

In procedural programming, the memory will be allocated at once and changes made in the data reflect the entire code whereas in object-oriented programming you can maintain separate sets of memories (copies)through different objects and changes made to the members of the class of one object will not affect class members of another object

Example:

main()
{
trish t1,t2,t3;
//t1 t2 t3 each have 8-byte separate memory space
t1.a=2;
t1.b=5;
t2.a=1;//t1.a and t3.a are unaffected
}

t1, t2, t3 three different objects the class trish each object holds separate copies of data members the class trish i.e ‘a’,’b’ of t1 is different from ‘a’,’b’ of t2 hence changes made in one object  will not affect others

Please Login/Signup to comment