C++ Classes And Objects

In the C++ programming language, classes and objects are the base building block that leads to object-oriented programming in C++ . They provide the code in a more organized, reusable, and maintainable way. In C++, classes act like a blueprint that defines how objects are structured and behave in the program. On the other hand, objects are instances of classes that are used to hold data and methods to create and manipulate several entities.

C++ Class

In C++, a class is a user-defined data type that acts as a blueprint to create an object. It is used to collect the data members and member functions into a single unit. A class keyword is used to create a class in C++. A class has several features, including fields, methods, constructors, etc.

For Example:

Consider a class of Cars. There can be several cars with different names and brands, but these cars will share many common properties, such as wheels, mileage range, Speed limit, and many others. It also contains turns, brakes, gears, accelerator, etc. Now, the Car is the class, and its data members are wheels, mileage range, and Speed limit, and its member functions are turn, brakes, gears, and accelerator.

Defining a Class:

A class should be defined and declared before its use in C++. It is defined via using the class keyword in C++. The body of the class is defined inside the curly brackets and terminated by a semicolon at the end.

Syntax:

It has the following syntax:

Example

class Class_Name {

    public: // Access specifier

    

    int data; // Data members

    // Member functions

    void display() {

        // code to be executed

    }

};

In this syntax,

  • Data Members: Data members are the variables that are defined inside the class of the program.
  • Member Functions: The functions that are declared inside a class are referred to as member method..
  • Access Specifiers: These are the keywords (such as public, private, and protected) that are used to control the accessibility of data members and methods.
  • C++ Class Example:

Let's take an example to demonstrate the class in C++.

Example

Example

#include <iostream>

using namespace std; //using standard namespace

// Define a class named Employee

class Employee {

public:

    // Data members

    string name;

    int age;

    // Member function

    void displayInfo() {

        cout << "Enter the Name: " << name << endl;

        

        cout << "Enter the Age: " << age << endl;

    }

};

int main() //Main function

{

    // Create an object of Employee

    Employee e1;

    // Assign values to data members

    e1.name = "John";

    e1.age =25;

    // Call member function

    e1.displayInfo();

    return 0;

}

Output:

Output

Enter the Name: John

Enter the Age: 25

Explanation:

In this example, we define a class named Employee with two public data members, name and age, and a member function displayInfo that displays the employee's details.

In the main function, an object e1 of the Employee class is created. The values "John" and 25 are assigned to the object's name and age. Finally, the displayInfo function is called to display these values.

Class Access Specifiers:

In C++ classes, the access specifiers can be used to control access to the members of the class. The access specifiers are also known as access modifiers in C++. These specifier keywords are defined in the class, and all the class members will have particular access levels under access specifiers.

There are mainly 3 types of access specifiers in C++.

  • Public: In C++, public data members may be accessed from outside the class using the dot (.) operator.
  • Private: Private data members may only be accessed within the class in C++. They cannot be accessed directly from outside the class.
  • Protected: A protected member variable of a class acts as a private member. It can be accessed inside the class and by derived classes.

To Read More: Access Specifiers in C++

C++ Object

An object represents a real-world entity, such as a chair, car, pen, mobile, or laptop. It consists of state (data) and behavior (function). Objects allow us to access the members of a class, and we can create more than one object from a single class.

In C++, an object is an instance of a class. When a class is declared in the program, no memory is allocated until an object of that class is created.

Creating Objects in C++:

Once the class is defined in the program, we can easily create its object in the same manner that we define the variable of any other built-in data types.

Example

class_Name object_Name;

Where,

  • class_Name: It represents the name of the Class.
  • object_Name: It represents the name of the class objects.

For Instance:

Example

Employee emp1, emp2;

Here, Employee is the class name and emp1 and emp2 are the object names.

Accessing Data Members:

In C++, class members may be accessed within the class directly by using their allocated name. If we need to access the class members outside the class, we can access its members using the dot(.) operator.

For Instance:

Example

obj.member1; //using for data members

obj.member2; //using for functions

obj.member...;

In this example, obj refers to the object name of the class, member1 represents the data member, and member2 represents the member function.

C++ Object Example:

Let's take an example to illustrate the objects in C++.

Example

Example

#include <iostream>

using namespace std; //using standard namespace

// Define a class

class CppTutorial {

public:

    string course;

    int duration;

    void showInfo() // Member function to show CppTutorial info

    {

        cout << "Name of the Course: " << course << endl;

        cout << "Time Duration of Course: " <<duration << " Year" << endl;

    }

};

int main() //main function

{

    

    CppTutorial CppTutorial1; // Create an object of CppTutorial

    CppTutorial1.course = "C++"; // Assign values to the object's data members

    CppTutorial1.duration = 1;

    CppTutorial1.showInfo(); // Call member function using the object

    return 0;

}

Output:

Output

Name of the Course: C++

Time Duration of Course: 1 Year

Explanation:

In this example, we have taken a class, CppTutorial, that has two data members and one function. CppTutorial1 is an object of the CppTutorial class. The object CppTutorial1 is used to access and manipulate class members using the dot (.) operator.

Characteristics of an Object:

Several characteristics of an Object in C++ are as follows:

  • State: It refers to the properties or data stored within the object. It defines the current condition or values stored in the object.
  • Behavior: It refers to the function that is related to an object. It defines what operations the object can perform. For example, a method to study (such as study) for a Student object, or a method to display the object's information (such as displayInfo)
  • Identity: Every object has a unique identity, and its properties are also identical to another object.
  • C++ Classes and Objects Example

Let's see an instance of a class that contains two fields: id and name. It creates an instance of the class, initializes the object, and prints the object value.

Example

Example

#include <iostream>  

using namespace std;  //using standard namespace

class Employee {  

   public:  

      int emp_id; //data member

      string emp_name; //data member

};  

int main() //main function 

{  

    Employee emp1; //creating an object of Employee   

    emp1.emp_id = 101;    

    emp1.emp_name = "John Miller";   

    cout<< emp1.emp_id  <<endl;  //print the employee id

    cout<< emp1.emp_name  <<endl;  //print the employee name

    return 0;  

}

Output:

Output

101

John Miller

Explanation:

In this example, we have taken a class named Employee that is defined with two public data members: empid and empname. In the main function, we create an obj emp1 of the type Employee. After that, the data members of the object are assigned values directly. The values of the object's members are accessed using the dot(.) operator.

C++ Class Example: Initialize and Display data through Method

Let's take another example of a C++ class where we are initializing and displaying objects through a method.

Example

Example

#include <iostream>  

using namespace std;  //using standard namespace

class Employee {  

   public:  //Access Modifier

       int emp_id; //data member

       string emp_name; 

       void insert(int i, string n)    

        {    

            emp_id = i;    

           emp_name = n;    

        }    

       void display()    

        {    

            cout<<emp_id<<"  "<<emp_name<<endl;    

        }    

};  

int main(void) //Main Function

{  

    Employee emp1; //Here, creates an Employee object

    Employee emp2; 

    emp1.insert(101, "John");    

    emp2.insert(102, "Alice");    

    emp1.display();    

    emp2.display();  

    return 0;  

}

Output:

Output

101  John

102  Alice

Explanation:

In this example, we have taken a class named Employee with members that give the employee's name and the ID number as type string and integer. In the main function, we define the value for emp1.id and emp2.id to 101 and 102, and the name to John and Alice.

C++ Class Example: Store and Display Employee Information

Let's take another example of a C++ class where we are storing and displaying employee information using the method.

Example

Example

#include <iostream>  

using namespace std;  //using standard namespace

class Employee {  

   public:  

       int emp_id; //data member

       string emp_name; //data member

       float emp_salary;  

       void insert(int i, string n, float s)    

        {    

           emp_id = i;    

           emp_name = n;    

            emp_salary = s;  

        }    

       void display()    

        {    

            cout<<emp_id<<"  "<<emp_name<<"  "<<emp_salary<<endl;    

        }    

};  

int main(void) //Main Function

{  

    Employee emp1; //Here, create an Employee object

    Employee emp2; 

    emp1.insert(101, "John",995000);    

    emp2.insert(102, "Michael", 29700);    

    emp1.display();    

    emp2.display();    

    return 0;  

}

Output:

Output

101  John  995000

102  Michael  29700

Objects as Function Arguments

If we need to pass an object to a function in C++, we may pass the object in the same manner as we pass any other primitive data. We only need to define the object in the function's argument and call the function.

Syntax:

It has the following syntax:

Example

function_name(object_name);

In this syntax, functionname refers to the name of the function, and objectname refers to the name of the object.

Example of Objects as Function Arguments:

Let's take an example to illustrate how to use objects as function arguments in C++.

Example

Example

#include <iostream>

using namespace std; //using standard namespace

class Employee {

public: //Access Modifiers

    string emp_name;

    int emp_id;

    void setDetails(string i, int j) {

        emp_name = i;

        emp_id = j;

    }

    void displayDetails() {

        cout << "Employee Name: " << emp_name << ", Employee ID: " << emp_id << endl;

    }

};

//Using a function that takes Employee object as parameter

void showEmployee(Employee emp) {

    // Using the object 'emp' to access its members

    cout << "Inside Function: " <<endl;

    cout << "Employee Name: " << emp.emp_name <<endl;

    cout << "Employee ID: " << emp.emp_id << endl;

}

int main() //Main Function

{

    Employee emp1;

    emp1.setDetails("John", 101);

    emp1.displayDetails();     // Call member function

    showEmployee(emp1);        // Pass object to function

    return 0;

}

Output:

Output

Employee Name: John, Employee ID: 101

Inside Function: 

Employee Name: John

Employee ID: 101

Explanation:

In this example, we define a class Employee that contains two data members: empname and empid. We also take a member function setDetails to assign values.

In the main function, an object emp1 is created and initialized with the employee name and id. After that, the object is passed to an external function showEmployee that takes an employee object as a parameter and prints its details.

Main differences between Classes and Objects in C++

Several main differences between classes and objects are as follows:

Features Classes Objects
Definition It is a blueprint for creating objects. It is an instance of a class with actual values.
Entity In classes, conceptual entities describe the structure and behavior. It is a real-world entity that is created from the class.
Syntax class Class_Name; class_Name obj;
Uses It is mainly used for concepts and models. It is mainly used for real-world entities, such as data and functionality.
Representation It represents a general concept or type. It represents a specific instance of a class.
Memory Allocation In C++ classes, no memory is allocated until an object is created. The object is created if an object is created in the program.

Conclusion

In conclusion, classes and objects are the main concepts of object-oriented programming (OOPs) in C++. A class is a user-defined function that works as a blueprint for creating an object. On the other hand, an object is an instance of a class that contains actual values. These concepts help model real-world entities, enhance code reusability, and improve program organization and maintainability.

C++ Classes and Objects MCQs

  1. What is the class in C++?
  • A collection of functions
  • A blueprint for creating objects
  • A method to define arrays of data
  • A reserved keyword in C++
  1. What is an object in C++?
  • An instance of a class
  • A method of data manipulation
  • A function inside a class
  • A variable of a fundamental data type
  1. How can we access the public members from outside the class?
  • Using the arrow (->) operator
  • Using the scope resolution operator
  • Using the dot (.) operator
  • Using a function only
  1. What is the correct default access specifier for members of a class in C++?
  • Protected
  • Public
  • Global
  • Private
  1. Which of the following keywords is used to define a class in C++?
  • class
  • object
  • define

Input Required

This code uses input(). Please provide values below: