Tutorial Study Image

Objects and Class in C++


December 22, 2022, Learn eTutorial
706

C++ is an object-oriented programming language that is mainly used to model real-world items into programs. Classes and objects are used in all object-oriented programming languages to accomplish this goal. Classes serve as a blueprint for the creation of objects having similar features. The essential principle that the object-oriented approach revolves around in C++ is the concept of classes and objects. It increases software efficiency by decreasing duplication of code and troubleshooting time.

With the guidance of a real-world example, you will now master the C++ concepts of class and object. For example, let's say you have a tiny library. All of the books in a library share some characteristics, such as book_name, author_name, and genre. Imagine that you wish to catalog every book in your library. You can construct a class called Book that acts as a template for all the books which is in your library rather than making distinct classes for every one of the books you own.

For example

Object Oriented Programming concepts: Student Class in C++

All students in school share some characteristics such as –(refer to the above figure)

  • Name
  • Roll No
  • Email ID
  • DOB
  • Weight

To define all of these characteristics, we can construct a class called student.

If a school has 2000 students, we would build 2000 objects that were specific to each kid in order to keep their information. A class in C++ is a data type that can have many objects or instances.

What do Classes mean in C++?

In C++, a class is a user-defined type or data structure that is mainly declared by using the keyword class and has data and functions as its members. Access to these members is controlled mainly by one of the 3 access specifiers such as private, protected, or public.

A class is a blueprint or template that connects an entity's features and functions. All entities or objects with similar types of attributes can be grouped together into what is known as a class. Encapsulation, data hiding, and abstraction are just a few of the fundamental ideas that classes further implement. In C++, a class is a data type that can have many objects or instances.

Object Oriented Programming concepts: Student Class in C++

How we will create a class?

The keyword class is used in order to create a class.

The syntax for declaring a class in C++


class class_name
{
    // class definition
    access_specifier:         // public, protected, or private                  
    data_member1;   // data members
    data_member2;           
    func1(){}       // member functions
    func2(){}  
};
 

Explanation

  • class: This keyword is mainly used to declare classes, and it is followed by the class name.
  • class_ name: This is the name of the class that is provided along with the keyword class.
  • access_ specifier: Before declaring the class members, the access specifier is provided. The access of the class members within the class is controlled by these specifiers. Specifiers may be protected, private, or public.
  • Data_member: These class variables serve as a place to store the data values.
  • member_function: The functions that have been declared inside the class are listed as member functions.

Example 1, let us create a class called “Myclass


class MyClass {       // class
  public:             // it is an access specifier
    int myNum;        // Attribute :int variable
    string myString;  // Attribute :string variable
};
 

Explanation

  • A class called MyClass is created using the keyword class.
  • In an access specifier, the public keyword indicates that a class's members (attributes and methods) are accessible to outsiders.
  • MyNum, an integer variable, and myString, a string variable, both exist within the class. Attributes are used to describe variables that are declared inside a class.
  • Finally, add a semicolon (;) to the end of the class definition.

Example 2


class Rect {
public:
    double length;
    double breadth;

    double calculateArea(){   
        return length * breadth;
    }
};
 

Explanation: Here, a class called Rect was defined.

Data members are the variable’s length and width that is defined inside the class. Additionally, the functions calculateArea() are referred to as the member functions of a class.

What do you mean by objects in C++?

Objects in C++ are equivalent to real-world entities. Suppose you are surrounded by objects all the time, including trees, insects, tables, benches, puppies, cars, and so on. These objects are related to some kind of properties and functions. Similarly, the concept of objects is present in C++ also. When a class is defined, it contains all the details about the objects that fall under that class type. It can construct similar objects that share the same information after defining the class, with the class name serving as the type specifier.

An object is mainly known as an instance of a class. No memory is allocated when a class is defined, but it is allocated when it is instantiated (i.e., when an object is formed or created). In C++, a class is defined by using the keyword class and the class name. 

Objects are produced at runtime and are runtime entities. Access to every class member is possible via an object. We must build objects in order to use the data and access the class's defined functions.

Syntax in order to define an object in C++


class class_name
class_name object_name;
 

The name of the class from which an object is to be formed is indicated by the class_name. The name that will be given to the new object is the object_ name. The following is how to make objects of the rect class, as stated in example 2 above:

Example 3 :


// sample function
void rectFunct() {
    // create objects
    Rect rect1, rect2;
}
int main(){
    // create objects 
    Rect rect3, rect4;
}
 

Explanation : Here, the function rectFunct() creates two objects of the Rect class, rect1, and rect2 . The objects rect3 as well as rect4 are created in the main in a similar manner.

As we can see, objects of a class can be created in any function of the program. We can also construct objects of a class within the class or in other classes. A single class also allows us in order to construct as many objects as we like.

Now let us write a C++ program by using the object and class

C++ program by using the object and class


// Program to illustrate the working of objects and class in C++ Programming
#include 
using namespace std;

// let us create a class name 'Rect' for the rectangle
class Rect {
   public:
    double length;
    double breadth;

    double calculateArea() {
        return length * breadth;
    }
};
int main() {

    // create an object of Rect class
    Rect rect1;

    // assign the values in to the data members
    rect1.length = 20;
    rect1.breadth = 60;

    // calculate as well as  display the area of the rectangle
    cout << "So the Area of Rectangle  is:  " << rect1.calculateArea() << endl;

    return 0;
}
 

Output:

So the Area of Rectangle  is:  1200

Explanation

In order to calculate the area of a room, we used the Rect class and its object rect1 in this program. We used the following code to assign the length and breadth values in main():

rect1.length = 20;
rect1.breadth = 60;

Then, in order to make the necessary computations, we invoked the function calculateArea().

It's important to note that the program uses the term public. This indicates that the users of the application can access the members from anywhere and they are public.