C++ Class And Objects

Classes and objects in c++ are used to support object-oriented concepts as 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.

What are classes and objects?

In a real-world example, we can think about a car. It is an object. It has four wheels, suitable color, and a brand name along with some functions like move, move forward and move back word all these attributes and the functions belong to a class of that object.  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++.

Syntax

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 a class is simply a model for creating objects. An object is created to get attributes and functions from that model. Its declaration is similar as we declare a variable but the only difference is that we replace 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: Classes and Objects in c++

// Class and object in C++
#include <iostream>
#include <string>
using namespace std;
class Car {
  public:
    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;
}

Output:

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

Leave a Reply