Class in C++

Class is a Collection of an Object in c++.

it is a user defined datatype in c++.

it is a Collection of Data Member and Member Function

it is similar as a Structure.

For Example in Real life The { Car } is a Class and { Volvo, Audi, Toyota } is an Object of a Class.

class and objects in cpp

The syntax to declare a class in c++ is :

class class_name
{
     private :
         variable declaration;
         function declaration;
            
     public :
         variable declaration;
         function declaration;
}; // the end of class must be declare semicolon symbol

Here’s an example of a class declaration in c++

class car
{
    int car_no; // This Member is Private Member
           
    public :
        char car_name[20]; // This Member is Public Member
};

Also read this :- Recursion in C++

Object in C++

The object is an Instant of Class.

the basic runtime entity that is used to access data member and member function.

it is a variable of a class.

To create an object of a car, specify the class name, followed by the object name.

To access the class attributes (car_no and car_name), use the dot syntax (.) on the object:

The syntax to declare an Object in c++ is :

class_name object_name;

Accessing a Class Member using an Object :

object_name.data member = value; // Assigning the value
object_name.function name(parameter);
object_name.data member; // Print the value

Example of Class and Object in C++.

#include <iostream>
using namespace std;
class item
{
   int item_no; // Private Member
   float cost;  // Private Member
 public:
   void getdata(int a, int b)
   {
      item_no = a;
      cost = b;
   }
   void putdata()
   {
      cout << "Item_no = " << item_no << endl;
      cout << "Cost = " << cost << endl;
   } 
};
int main()
{
   item i1, i2;
   i1.getdata(101, 5000);
   i2.getdata(102, 2000);
   cout << " I1 Object : " << endl;
   i1.putdata();
   cout << " I2 Object : " << endl;
   i2.putdata();
   return 0;
}

output

I1 Object : Item_no = 101 Cost = 5000 I2 Object : Item_no = 102 Cost = 2000
Â