C++ is an object-oriented language that is used to model real-world entities into programs. All object-oriented programming languages achieve this task using classes and objects. Classes act as a blueprint to create objects with similar properties. The concept of classes and objects in C++ is the fundamental idea around which the object-oriented approach revolves around. It enhances the program’s efficiency by reducing code redundancy and debugging time. 

Now, you will understand the concept of the class and object in C++ with the help of a real-life example. Suppose you have a small library. In a library, all books have some common properties like book_name, author_name, and genre. Now imagine you want to create a catalog of all the books in your collection. Instead of creating separate classes for every book you own, you can create a Book class that serves as a template for all the books in your library.

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

What are Classes in C++? 

A class is a template or a blueprint that binds the properties and functions of an entity. You can put all the entities or objects having similar attributes under a single roof, known as a class. Classes further implement the core concepts like encapsulation, data hiding, and abstraction. In C++, a class acts as a data type that can have multiple objects or instances of the class type.  

Consider an example of a railway station having several trains. A train has some characteristics like train_no, destination, train_type, arrival_time, and departure_time. And its associated operations are arrival and departure. You can define a class can for a train as follows:

class train

{

    // characteristics

    int train_no;

    char destination;

    char train_type;

    int arrival_time;

    int departure_time; 

    // functions

    int arrival(delayed_time)

    {

        arrival_time += delayed_time;

        return arr_time;

    } 

    int departure(delayed_time)

    {

        departure_time += delayed_time;

        return departure_time;

    }

The above class declaration contains properties of the class, train_no, destination, train_type, arrival_time, and departure_time as the data members. You can define the operations, arrival, and departure as the member functions of the class.

Syntax to Declare 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(){}  

};

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

Description of the Syntax:

  • class: This is the keyword used to declare a class that is followed by the name of the class.
  • class_name: This is the name of the class which is specified along with the keyword class.
  • access_specifier: It provides the access specifier before declaring the members of the class. These specifiers control the access of the class members within the class. The specifiers can be public, protected, and private.
  • data_member: These are the variables of the class to store the data values.
  • member_function: These are the functions declared inside the class.

What are Objects in C++? 

Objects in C++ are analogous to real-world entities. There are objects everywhere around you, like trees, birds, chairs, tables, dogs, cars, and the list can go on. There are some properties and functions associated with these objects. Similarly, C++ also includes the concept of objects. When you define a class, it contains all the information about the objects of the class type. Once it defines the class, it can create similar objects sharing that information, with the class name being the type specifier.

Consider the example of a railway station discussed in the previous section. After defining the class train, you can create similar objects for this class. For example, train_A and train_B. You can create the objects for the class defined above in the following way:

    train train_A, train_B;

The syntax to create objects in C++:

    class_name object_name;

The object object_name once created, can be used to access the data members and member functions of the class class_name using the dot operator in the following way:

    obj.data_member = 10;   // accessing data member

    obj.func();             // accessing member function

Significance of Class and Object in C++

The concept of class and object in C++ makes it possible to incorporate real-life analogy to programming. It gives the data the highest priority using classes. The following features prove the significance of class and object in C++:

  • Data hiding: A class prevents the access of the data from the outside world using access specifiers. It can set permissions to restrict the access of the data.
  • Code Reusability:  You can reduce code redundancy by using reusable code with the help of inheritance. Other classes can inherit similar functionalities and properties, which makes the code clean.
  • Data binding: The data elements and their associated functionalities are bound under one hood, providing more security to the data.
  • Flexibility: You can use a class in many forms using the concept of polymorphism. This makes a program flexible and increases its extensibility.

Member Functions in Classes 

The member functions are like the conventional functions. It defines these methods inside a class and has direct access to all the data members of its class. When you define a member function, it only creates and shares one instance of that function by all the instances of that class. The following syntax can be used to declare a member function inside a class:

class class_name

{

access_specifier:

    return_type member_function_name(data_type arg);

};

It specifies the access specifier before declaring a member function. It also specifies the return type and data type in the same way in which it declares a usual function.

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

Method Definition Outside and Inside of a Class

The following two ways can define a method or member functions of a class:

  1. Inside class definition
  2. Outside class definition 

The function body remains the same in both approaches to define a member function. The difference lies only in the function's header. Now, have a deeper understanding of these approaches.

Inside Class Definition

This approach of defining a member function is generally preferred for small functions. It defines a member function inside a class in the same familiar way as it defines a conventional function. It specifies the return type of the function, followed by the function name, and it provides arguments in the function header. Then it provides the function body to define the complete function. The member functions that are defined inside a class are automatically inline. The following example illustrates defining a member function inside a class.

#include <iostream>

using namespace std;

// define a class

class my_class

{

public:

    // inside class definition of the function 

    void sum(int num1, int num2)                // function header

    {   

        cout << "The sum of the numbers is: ";  // function body

        cout << (num1 + num2) << "\n\n";   

    }

};

int main()

{

    // create an object of the class

    my_class obj;

    // call the member function

    obj.sum(5, 10);

    return 0;

}

ObjectsInCpp_1 

In the above example, you define the function sum() inside the class my_class. The function is automatically an inline function. Whenever you call this function by an object of its class, it inserts the code of the function’s body there, which reduces the execution time of the program. Here, the statement obj.sum(5, 10) is replaced by the body of the function sum().

Outside Class Definition

Here, you use the scope resolution operator (::) to define a member function outside its class. Even though you define the member function outside the class, it still needs to be declared first inside the class. This approach of defining a member function of a class is the most preferred. The following syntax is used to define a member function outside its class:

void class_name :: function_name(arguments)

{

// function body

}

The class_name is the name of the class in which the function has been declared. The function_name is the name of the member function. It uses the scope resolution operator here to restrict the scope of the function to its class.

The following example illustrates how to define a member function outside a class.

#include <iostream>

using namespace std; 

// define a class

class my_class

public:

    // declare the member function

    void sum(int num1, int num2);

}; 

// outside class definition of the function

void my_class::sum(int num1, int num2) // function header

{

    cout << "The sum of the numbers is: "; // function body

    cout << (num1 + num2) << "\n\n";

int main()

{

    // create an object of the class

    my_class obj;

    // call the member function

    obj.sum(5, 10); 

    return 0;

}

ClassesAndObjectsInCpp_2

In the above example, it first declares the function sum() inside the class my_class. It then defines the member function outside the class specifying the class name, followed by the scope resolution operator. The function body remains the same as in the inside class definition of the function.

Array of Objects

In C++, you can declare an array of any data type. This also includes the class type. The Array of objects is an array containing the elements of the class type. The definition of an array of objects is similar to the usual array definition with the data type replaced with the class name. The following syntax is used to define an array of objects:

class_name obj[20];

The array obj contains 20 elements of the type class_name. These elements are, obj[1], obj[2], obj[3], …… obj[20]. An array of objects is preferred when there is a requirement for numerous objects of the same class. Instead of creating obj1, obj2, obj3,....obj20, you can simply declare obj[20]. 

The following example illustrates the use of an array of objects.

#include <iostream>

using namespace std;

// define a class

class my_class

{

public:

    // declare the member function

    void printValue(int value)

    {

        cout << "The value is: " << value << "\n";

    }

};

int main()

{

    // create an object of the class

    my_class obj[5]; 

    // call printValue() function for all objects

    for (int i = 0; i < 5; i++)

    {

        obj[i].printValue(2 * i); // printValue() is called

                                  // for particular object

    } 

    cout << "\n\n"; 

    return 0;

}

ClassesAndObjectsInCpp_3  

In the above example, obj[5] is an array of objects, containing 5 elements. This is used to involve the printValue() function five times for a particular object to print a particular value.

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

Objects as Function Arguments

In C++, you can pass the objects of a class as arguments in the same way you pass a variable to a function as arguments. An object can be passed as an argument to a member function, a friend function, and a non-member function. The private and public members of the object are accessible to the member function and the friend function. However, the non-member function is only allowed to access the public members of the object.

You can pass the objects as arguments in the following ways:

  1. Passing objects by value
  2. Passing objects by reference

Let us understand both ways of passing an object as function arguments.

Passing Objects by Value

You can pass objects using the “call by value mechanism” to a function as arguments. Only the value of the object is passed to the function. It makes a separate copy of the object for the function. Any modifications done by the function to the object members do not modify the original object. The following example illustrates how to pass objects by value as arguments.

#include <iostream>

using namespace std;

// class to convert temperature

// from fahrenheit to celsius

class convTemperature

{

public:

    float f, c;

    void getTemp(float value)

    {

        f = value;

    }

    // function that accepts object as argument

    void findTemp(convTemperature obj)

    {

        obj.c = ((obj.f - 32) * 5) / 9;

        cout << "\nThe temperature in celsius is: " << obj.c << "\n";

    }

};

int main()

{

    // create objects of the class

    convTemperature obj1;

    obj1.getTemp(100);

    obj1.findTemp(obj1); // pass obj1 by value

    // garbage value of c will be printed

    // as the object was passed by value

    cout << "The value of c (object's copy) is: " << obj1.c << "\n"; 

    cout << "\n";

    return 0;

}

ClassesAndObjectsInCpp_4

In the above example, the object obj1 of the class convTemperature is passed by value to the function findTemp(). The calculates the temperature in celsius and updates the value of the member variable “c”. Since it passes the object by value, it only updates the function’s version of “c” and the variable “c” of the object’s copy remains unaffected. Therefore, the statement  obj1.c prints a garbage value.

Passing Objects by Reference

The other way of passing an object as an argument is by using the “call by reference mechanism”. In this case, the memory address of the object is passed as an argument. So the function directly accesses the object and its members. All the modifications by the function are now done to the original members of the object. The following example illustrates how to pass objects by reference as arguments.

#include <iostream>

using namespace std;

// class to update the value of the data member 

class my_class

{

public:

    int x 

    // function that accepts object as argument

    void updateValue(my_class &obj)

    {

        obj.x = 100;

        cout << "\nThe modified value of x is: " << obj.x << "\n";

    }

};

int main()

{

    // create an object of the class

    my_class obj;

    obj.updateValue(obj); // pass obj by reference

    // same value of x will be printed 

    // as the object was passed by reference

    cout << "The value of x (object's copy) is: " << obj.x << "\n";

    cout << "\n";

    return 0;

}

ClassesAndObjectsInCpp_5

In the above example, you pass the object obj of the class my_class by reference to the function updateValue(). The function gets direct access to the memory address of the object obj.  When the function makes a modification to the member variable “x” using the statement obj.x = 100, the original object gets modified. Therefore, the following statement now prints the same modified value of x.

cout << obj.x

Learn From The Best Mentors in the Industry!

Automation Testing Masters ProgramExplore Program
Learn From The Best Mentors in the Industry!

Difference Between Class and Structure

Although a class and a structure may seem identical, they differ from each other to a great extent. Now, you will understand how a class differs from a structure in C++.

Class:

A class can be defined as a user-defined data type that contains some data members and member functions whose access is regulated by the specified access specifiers. 

The following program illustrates the working of a class in C++:

#include <iostream>

using namespace std;

class my_class

{

    //members are private by default

    int member1;

    int member2;

public:

    //default constructor

    my_class()

    {

        member1 = 10;

        member2 = 20;

    }

    //function printing the values of private data members

    void print()

    {

        cout << "Value of member1 is: " << member1 << endl;

        cout << "Value of member2 is: " << member2 << endl;

    }

};

int main()

{

    my_class obj;

    obj.print();

}

ClassesAndObjectsInCpp_6

Structure:

A structure can be defined as a user-defined data type that is used to group elements of different data types together. 

The following program illustrates the working of a structure in C++:

#include <iostream>

using namespace std;

struct my_structure

{

    //members are public by default

    int member1;

    int member2; 

    //assigning values to the data members

    my_structure()

    {

        member1 = 10;

        member2 = 20;

    }

    //function printing the values of public data members

    void print()

    {

        cout << "Value of member1 is: " << member1 << endl;

        cout << "Value of member2 is: " << member2 << endl;

    }

};

int main()

{

    my_structure obj;

    obj.print();

ClassesAndObjectsInCpp_7

The following table highlights the key differences between a class and a structure in C++. 

Class 

Structure

A class is defined using the class keyword.

A structure is defined using the structure keyword.

All the data members, as well as the member functions of a class, are private by default.

All the data members, as well as the member functions of a structure, are public by default.

Concepts of OOPs like data abstraction and data encapsulation are supported by classes.

Structures do not support any concept of OOPs.

A class can have a NULL value.

A structure can not acquire a NULL value.

You cannot implement classes in the C language.

You can implement structures in C as well as C++ language.

Members of a class can be specified as public and protected too.

Members of a structure can only be public and can not be specified as private or protected.

A Heap is used for allocating the memory of a class.

A Stack is used for allocating the memory of a structure.

Learn 15+ In-Demand Tools and Skills!

Automation Testing Masters ProgramExplore Program
Learn 15+ In-Demand Tools and Skills!

Final Thoughts!

To sum up quickly, in this article, you learned about the ins and outs of classes and objects in C++. You started with a brief introduction to the descriptions of classes and objects in c++, their significance in the real world, and the syntax to declare them. 

You gradually moved on to advanced topics such as access modifiers, constructors and destructors, assignment operators, this pointer, etc. Finally, you ended the article with concepts such as member functions used inside classes and their real-world usage, creating an array of objects, passing objects as arguments to functions, and the difference between a class and a structure.

You can learn more about such important C++ concepts in our beginner’s guide to C++. This guide will take you through all the fundamentals and key concepts in C++.

If you want to pursue a career in full-stack web development, you should definitely try Simplilearn’s 9-month training program on Full Stack Web Development in Java. This course structure is carefully crafted by industry experts who are available to you as mentors throughout your journey to solve your doubts and queries. At the end of this course, you will have mastered all the top trending skills that are in high demand including DevOps, Agile, Java, and its frameworks such as spring, hibernate, JPA, etc, front-end languages such as HTML, CSS, JS, servlets, etc.

Happy Learning!