In the C++ coding language, classes and objects serve as the fundamental foundation that paves the way for implementing object-oriented programming in C++. They offer a structured, reusable, and sustainable approach to writing code. Within C++, classes function as a template outlining the structure and behavior of objects within the program. Conversely, objects represent specific occurrences of classes that store information and functions to generate and control multiple entities.
C++ Class
In C++, a class represents a custom data type serving as a template for object creation. It consolidates data members and member functions into a cohesive entity. The class keyword is employed to define a class in C++. Notable attributes of a class encompass fields, methods, constructors, and more.
For Example:
Consider a category of Vehicles. Within this category, numerous vehicles can exist with varying names and manufacturers. Despite these differences, these vehicles will possess numerous similar characteristics like wheels, fuel efficiency range, maximum speed, and more. Additionally, they will feature functions like turning, braking, shifting gears, accelerating, and so forth. In this context, the Vehicle acts as the class, with attributes including wheels, fuel efficiency range, and maximum speed, while its methods consist of turning, braking, shifting gears, and accelerating.
Defining a Class:
A class in C++ must be declared and defined prior to its utilization. It is declared by employing the class keyword in C++. The class body is enclosed within curly braces and concluded with a semicolon.
Syntax:
It has the following syntax:
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 consider an example to illustrate the class concept in C++.
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:
Enter the Name: John
Enter the Age: 25
Explanation:
In this instance, we establish a class titled Employee containing two accessible data attributes, namely name and age, along with a method named displayInfo responsible for presenting the employee's information.
Within the main function, an instance e1 belonging to the Employee class is instantiated. The attributes "John" and 25 are set as the values for the object's name and age correspondingly. Subsequently, the displayInfo method is invoked to exhibit these values.
Class Access Specifiers:
In C++ classes, access specifiers play a crucial role in managing the accessibility of class members. These specifiers, also referred to as access modifiers in C++, are specified within the class to assign specific access levels to its members.
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 embodies a tangible entity from the physical world, such as a chair, car, pen, mobile device, or laptop. It encompasses both state, which refers to its data, and behavior, which pertains to its functions. Objects provide us with the capability to interact with the attributes of a class, enabling the creation of multiple instances from a singular class.
In C++, an object represents a specific occurrence of a class. Memory is not reserved for a class until an object of that class is instantiated within the program.
Creating Objects in C++:
After defining the class within the program, creating an object of the class follows a similar syntax to declaring a variable of standard data types.
class_Name object_Name;
Whereas,
- class_Name: This signifies the identifier of the Class.
- object_Name: This denotes the identifier of the class instances.
For Instance:
Employee emp1, emp2;
Here, "Employee" represents the class while "emp1" and "emp2" are instances of the class.
Accessing Data Members:
In C++, class members are accessible within the class directly by using their allocated name. When it is necessary to reach the class members outside the class, we can do so by utilizing the dot (.) operator.
For Instance:
obj.member1; //using for data members
obj.member2; //using for functions
obj.member...;
In this instance, obj denotes the object name within the class, member1 signifies the data member, and member2 denotes the member function.
C++ Object Example:
Let's consider an example to demonstrate the concept of objects in C++.
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:
Name of the Course: C++
Time Duration of Course: 1 Year
Explanation:
In this instance, we are examining a class named CppTutorial, which contains a pair of data attributes and a single method. CppTutorial1 represents an instance of the CppTutorial class. This particular instance, CppTutorial1, is employed to interact with and modify class attributes by employing 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 consider an example of a class that includes two attributes: id and name. This class instantiates an object, sets initial values to the object, and displays the object's value.
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:
101
John Miller
Explanation:
In this instance, we are considering a class called Employee which contains two public attributes: empid and empname. Within the main function, an instance named emp1 of the Employee class is instantiated. Subsequently, the attributes of the instance are initialized directly. Access to the instance's attributes is achieved through the dot (.) operator.
C++ Class Example: Initialize and Display data through Method
Let's consider a different instance involving a C++ class, where we initialize objects and showcase them using a function.
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:
101 John
102 Alice
Explanation:
In this instance, we are illustrating a scenario where a class called Employee is created with attributes specifying the employee's name and ID number, represented by string and integer data types. Within the main function, we assign the values 101 and 102 to emp1.id and emp2.id, along with the names John and Alice respectively.
C++ Class Example: Store and Display Employee Information
Let's consider another instance of a C++ class where we are saving and presenting employee details utilizing the function.
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:
101 John 995000
102 Michael 29700
Objects as Function Arguments
If there is a necessity to transmit an object to a function in C++, the object can be transmitted in a similar manner as primitive data types. It involves specifying the object in the function's parameter and then invoking the function.
Syntax:
It has the following syntax:
function_name(object_name);
In this particular syntax, functionname is the designated term for the function's name, while objectname is the specific term used for the object's name.
Example of Objects as Function Arguments:
Let's consider an example to demonstrate the usage of objects as parameters in C++ functions.
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:
Employee Name: John, Employee ID: 101
Inside Function:
Employee Name: John
Employee ID: 101
Explanation:
In this instance, we establish a class named Employee, which includes two attributes: empname and empid. Additionally, a method setDetails is implemented to set these values.
In the main function, we instantiate an object emp1, setting it up with the employee's name and identification number. Subsequently, we transfer this object to an external function showEmployee, which accepts an employee object as an argument and displays its specific information.
Main differences between Classes and Objects in C++
Several key variances between classes and objects are outlined below:
| 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 summary, classes and objects serve as the fundamental principles of object-oriented programming (OOPs) in C++. A class functions as a custom-defined template for generating an object. Conversely, an object represents a specific occurrence of a class with concrete data values. These principles aid in simulating real-life entities, boosting code recyclability, and enhancing the structure and sustainability of programs.
C++ Classes and Objects MCQs
- 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++
- 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
- 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
- What is the correct default access specifier for members of a class in C++?
- Protected
- Public
- Global
- Private
- Which of the following keywords is used to define a class in C++?
- class
- object
- define