C++ Classes And Objects

C++ Classes and objects are used to support object-oriented concepts. This is the key feature of the c++ programming language.  In this concept, the code is divided into classes and objects. It is useful in terms of reusability and understanding of the code.

cpp classes and objects

What are C++ classes and objects?

In a real-world example, we can think about a vehicle. It has many objects like trucks, cars, buses, motorbikes and so on. Similarly, if we consider a car as a class. It has many objects like BMW, Tesla, Honda, etc. We can create as many objects from the class as we can with different attribute values.

Classes in c++

Classes are the actual collection of attributes and functions upon which objects are created. The class declaration starts with the keyword “class” followed by an identifier.  Here is the syntax of the class in c++.


Class car
Body of the class

Note: Class is declared similar to the declaration of structure. Don’t forget to add a semicolon after the closing parenthesis.

Object in c++

As the class is simply a model for creating objects. While an object is created to get attributes and functions from that model. Its declaration is similar to declaring a variable but the only difference is that we replace the data type with the class name. Here is the syntax to create an object.

Car obj;

This object contains all the attributes and functions defined in the class car.

Example: C++ Classes and Objects

// Class and object in C++
#include <iostream>
#include <string>
using namespace std;
class Car {
    string brand;   
    int model;
    string color;
    int price;

int main() {
  //Car object 1
  Car car1;
  car1.brand = "Ford";
  car1.model = 2021;
  car1.color = "red";
  car1.price = 250000;
  //Car object 2
  Car car2;
  car2.brand = "Tesla";
  car2.model = 2022;
  car2.color = "black";
  car2.price = 450000;

  cout << "Car Brand: "<<car1.brand<<endl;
  cout << "Car Model: "<<car1.model<<endl;
  cout << "Car Color: "<<car1.color<<endl;
  cout << "Car Price: "<<car1.price<<endl;
  return 0;


Car Brand: Ford
Car Model: 2021
Car Color: red
Car Price: 250000

Recommended Articles

C++ student grade program

C++ If-else Statements