Classes and Objects In C++ with Example

Classes and Objects In C++ with Example

Through the use of examples, we will learn about objects and classes in this tutorial and how to utilize them in C++.

A class is the fundamental unit of Object-Oriented programming in C++. It is a user-defined data type that may be utilized by creating an instance of the class in order to access and use its data members and member functions.

A C++ class functions as an object’s blueprint.
For instance: Think about the car class. There may be numerous automobiles with various names and brands, but they all have some characteristics, such as having four wheels, a speed limit, a mileage range, etc. In this case, a car is a class

its features include its wheels, speed limitations, and mileage.

A class is a data type that the user defines and has both data members and member functions.

We studied functions and variables in earlier courses. Sometimes it’s preferable to group together related functions and data for logical and practical reasons.

Let’s say we need to determine the area and volume of a rectangle space and need to store the length, width, and height.

Three variables, such as length, width, and height, as well as the functions calculateArea() and calculateVolume can be created to complete this assignment ().

However, in C++, we may also wrap these related data and functions in a single place rather of generating distinct variables and functions (by creating objects). This programming paradigm is known as object-oriented programming in Classes and Objects.

However, we must first understand classes in order to construct and use objects in C++.

C++ Class

A class is the object’s design manual.

A class can be compared to a rough draught or prototype of a home. It includes all of the information regarding the floors, doors, windows, etc. We construct the house in accordance with these descriptions. The item is a house.

Create a Class

In C++, a class is defined by using the keyword class and the class name.

Inside the curly braces and following a comma, the class’s body is defined.

class className {
   // some data
   // some functions
};

For example,

class Room {
    public:
        double length;
        double breadth;
        double height;   

        double calculateArea(){   
            return length * breadth;
        }

        double calculateVolume(){   
            return length * breadth * height;
        }

};

Here, a class called Room was defined.

Data members are the length, breadth, and height-defined variables inside the class. As member functions of a class, calculateArea() and calculateVolume() are also recognised.

C++ Objects

No memory or storage is allocated when a class is defined; only the object’s specification is defined.

We must build objects in order to use the data and access the class’s defined functions.

Syntax to Define Object in C++ Classes and Objects

className objectVariableName;

As shown in the example above, we may produce objects of the Room class by doing the following:

// sample function
void sampleFunction() {
    // create objects
    Room room1, room2;
}

int main(){
    // create objects 
    Room room3, room4;
}

Here, the sampleFunction creates two instances of the Room class, room1 and room2 (). The objects room3 and room4 are generated in the main in a similar manner ().

As we can see, any program function allows us to generate objects of a class. A class’s objects can also be created within the class or in other classes.

Additionally, we can generate as many objects from a single class as we like.

C++ Access Data Members and Member Functions of Classes and Objects

Using the. (dot) operator, we may access the data members and member functions of a class. For instance,

room2.calculateArea();

This will activate the calculateArea() method for object room2 in the Room class.

The data members can also be retrieved as follows:

room1.length = 5.5;

In this instance, it sets room1’s length variable to 5.5.

Example 1: Objects and Classes in C++ Programming

// Program to illustrate the working of
// objects and class in C++ Programming

#include <iostream>
using namespace std;

// create a class
class Room {

   public:
    double length;
    double breadth;
    double height;

    double calculateArea() {
        return length * breadth;
    }

    double calculateVolume() {
        return length * breadth * height;
    }
};

int main() {

    // create object of Room class
    Room room1;

    // assign values to data members
    room1.length = 42.5;
    room1.breadth = 30.8;
    room1.height = 19.2;

    // calculate and display the area and volume of the room
    cout << "Area of Room =  " << room1.calculateArea() << endl;
    cout << "Volume of Room =  " << room1.calculateVolume() << endl;

    return 0;
}

Output

Area of Room = 1309
Volume of Room = 25132.8

To determine the area and volume of a room, we used the Room class and its object room1 in this application.

We assigned the values for length, breadth, and height using the following code in main():

room1.length = 42.5;
room1.breadth = 30.8;
room1.height = 19.2;

Then, to make the necessary computations, we used the functions calculateArea() and calculateVolume().

Take note of the program’s use of the keyword public. This indicates that the users of the application can access the members wherever.

Using the private keyword, we can also establish private members based on our requirements. Only from within the class can one access the secret members. For instance,

class Test {

private:
    int a;
    void function1() { }

public:
    int b;
    void function2() { }
}

A and function1() are private in this case. As a result, they are inaccessible to users outside the class.

B and function2(), on the other hand, are reachable from everywhere in the program.

Please visit our C++ Class Access Modifiers tutorial to learn more about public and private keywords.

Example 2: Using public and private in Classes and Objects

// Program to illustrate the working of
// public and private in C++ Class

#include <iostream>
using namespace std;

class Room {

   private:
    double length;
    double breadth;
    double height;

   public:

    // function to initialize private variables
    void initData(double len, double brth, double hgt) {
        length = len;
        breadth = brth;
        height = hgt;
    }

    double calculateArea() {
        return length * breadth;
    }

    double calculateVolume() {
        return length * breadth * height;
    }
};

int main() {

    // create object of Room class
    Room room1;

    // pass the values of private variables as arguments
    room1.initData(42.5, 30.8, 19.2);

    cout << "Area of Room =  " << room1.calculateArea() << endl;
    cout << "Volume of Room =  " << room1.calculateVolume() << endl;

    return 0;
}

Output

Area of Room = 1309
Volume of Room = 25132.8

The only difference between the aforementioned example and the first example is that the class variables are now private.

We cannot access the variables directly from main because they are now private (). Consequently, it would be improper to use the following code:

// invalid code
obj.length = 42.5;
obj.breadth = 30.8;
obj.height = 19.2;

Instead, we initialise the private variables using the double len, double brth, and double hgt function parameters of the public method initData().

Visit these pages to learn more about objects and classes:

C++ Continue Statement with Example | C++ Programming

Features of C++ | C++ Tutorial

Leave a Reply