Classes in C++

A class in C++ is the building block, that leads to Object-Oriented programming. It can hold its own data members and member functions. It is a also a user-defined datatype which acts like a blueprint for an object.

In C++ we can wrap related data and functions into a single place by creating objects. This type of programming model is known as object-oriented programming.

We can think of a class as a sketch of a house. All the details about the floors, doors, windows, etc are in the house. Based on these descriptions we build the house and house is the object.

Create a Class

In C++ a class is defined using keyword class which is followed by the name of the class. The body of the class is defined within curly brackets and it is ended with a semicolon.

Syntax:

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

Example:

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

        double calculateArea(){   
            return length * breadth;
        }

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

};

Here, we have defined a class called Hall.

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

Class Member Functions

A class member function is defined as a function that has its definition within the class definition like any other variable. It operates on any object of the class of which it is a member. Also, it has access to all the members of a class for that object.

Example: accessing the members of the class using a member function

class Cuboid {
   public:
      double length;         // Length of a cuboid
      double breadth;        // Breadth of a cuboid
      double height;         // Height of a cuboid
      double getVolume(void);// Returns cuboid volume
};

You can be define member functions within the class definition or separately using the scope resolution operator. Member function defined within the class definition declares the function inline, even when the inline specifier is not used. Hence, you can define Volume() function in the following ways:

class Cuboid {
   public:
      double length;      // Length of a cuboid
      double breadth;     // Breadth of a cuboid
      double height;      // Height of a cuboid
   
      double getVolume(void) {
         return length * breadth * height;
      }
};
                                                                           OR

Using the scope resolution operator (::) –

double Cuboid::getVolume(void) {
   return length * breadth * height;
}

Here, the only important point is that you would have to use class name just before :: operator.

We will be happy to hear your thoughts

Leave a reply

Edusera
Logo
Open chat
1
Scan the code
Hello!👋
Can we help you?