C++ Classes and Objects

C++ Classes and Objects

C++ Classes and Objects

In this tutorial, we will find out about objects and classes and how to use them in C++ with the help of examples.

In the past tutorials, we found out about functions and variables. In some cases it’s attractive to place related capacities and information in one spot so it’s coherent and simpler to work with.

Assume, we have to store the length, broadness, and stature of a rectangular room and ascertain its territory and volume.

To handle this task, we can make three variables say, length, breadth, and height alongside the functions calculateArea() and calculateVolume().

However, in C++, as opposed to making separate variables and functions, we can likewise enclose this related information and capacities by a solitary spot (by making objects). This programming worldview is known as object-oriented programming.

Be that as it may, before we can make objects and use them in C++, we first need to find out about classes.


C++ Class

A class is a blueprint for the object.

We can think about a class as a sketch (model) of a house. It contains all the insights regarding the floors, entryways, windows, and so forth. In view of these portrayals, we assemble the house. House is the object

Create a Class

A class is defined in C++ using the 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 {
   // 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, we defined a class named Room.

The variables length, breadth, 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

At the point when a class is characterized, just the particular for the article is characterized; no memory or capacity is allocated. To use the data and access functions characterized in the class, we need to create objects.


Syntax to Define Object in C++

className objectVariableName;

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

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

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

Here, two objects room1 and room2 of the Room class are created in sampleFunction(). Similarly, the objects room3 and room4 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,

room2.calculateArea();

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

Similarly, the data members can be accessed as:

room1.length = 5.5;

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


Example 1: Object and Class 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

In this program, we have used the Room class and its object room1 to calculate the area and volume of a room.

In main(), we assigned the values of length, breadth, and height with the code:

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

We at that point called the capacities calculateArea() and calculateVolume() to perform the necessary calculations.

Note the use of the watchword open in the program. This implies the individuals are open and can be gotten to anyplace from the program.

According to our necessities, we can likewise make private individuals using private watchword. The private members of a class can be accessed from within the class. For instance,

class Test {

private:
 int a;
    void function1() { }

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

Here, a and function1() are private and are. Thus they cannot be accessed from outside the class.

On the other hand, b and function2() are accessible from everywhere in the program.


Example 2: Using public and private in C++ Class

// 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 getData(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.getData(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 above example is almost indistinguishable from the first example, then again, actually, the class factors are currently private.

Since the factors are currently private, we can’t access them straightforwardly from the main(). Subsequently, using the accompanying code would be invalid:

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

Instead, we use the public function getData() to initialize the private variables via the function parameters double len, double brth, and double hgt.


Please feel free to give your comment if you face any difficulty here.

Leave a Reply

Your email address will not be published. Required fields are marked *