C++ Classes and Objects

by anupmaurya
0 comment

C++ Class

Class is a user-defined data type, which holds its own data members and member functions, which can be accessed and used by creating an instance of that class. A C++ class is like a blueprint for an object.

We can think of a class as a sketch (prototype) of a house. It contains all the details about the floors, doors, windows, etc. Based on these descriptions we build the house. House is the object.

Create a Class

A class is defined in C++ using keyword class followed by the name of the class.

The body of the class is defined inside the curly brackets and terminated by a semicolon at the end.

class className { // data members // member functions };
Code language: C++ (cpp)


class Shape { public: double length; double breadth; double height; double calculateArea(){ return length * breadth; } double calculateVolume(){ return length * breadth * height; } };
Code language: C++ (cpp)

Here, we defined a class named Shape.

The variables lengthbreadth, and height declared inside the class are known as data members. And, the functions calculateArea() and calculateVolume() are known as member functions of a class.

C++ Objects

In C++, Object is a real world entity, for example, chair, car, pen,television, cup, etc.

In other words, object is an entity that has state and behavior. Here, state means data and behavior means functionality.

When a class is defined, only the specification for the object is defined; no memory or storage is allocated.

Object is a runtime entity, it is created at runtime.

Object is an instance of a class. All the members of the class can be accessed through object.

Syntax to Define Object in C++

className objectVariableName;
Code language: C++ (cpp)

We can create objects of Room class (defined in the above example) as follows:

// sample function void sampleFunction() { // create objects Shape shape1, shape2; } int main(){ // create objects Shape shape2, shape3; }
Code language: C++ (cpp)

Here, two objects shape1 and shape2 of the Shape class are created in sampleFunction(). Similarly, the objects shape3 and shape4 are created in main().

As we can see, we can create objects of a class in any function of the program. We can also create objects of a class within the class itself, or in other classes.

Also, we can create as many objects as we want from a single class.

C++ Access Data Members and Member Functions

We can access the data members and member functions of a class by using a . (dot) operator. For example,

Code language: C++ (cpp)

This will call the calculateArea() function inside the Room class for object room2.

Similarly, the data members can be accessed as:

shape1.length = 5.5;
Code language: C++ (cpp)

In this case, it initializes the length variable of shape1 to 5.5.

You may also like