C++ represents an object-oriented programming language that prioritizes data organization and its handling. It promotes modular programming by enabling the segmentation of memory into distinct sections for data and functions. In C++, structures and classes facilitate the development of personalized data types that can subsequently be employed to generate instances or objects.
Both structures and classes share many similarities, yet they possess distinct characteristics in how they function. Prior to delving into these disparities, it is beneficial to grasp the basic concepts of C++ structures and classes.
What is Structure in C++?
In C++, a structure is a custom data type created by the user that enables the grouping of variables of various types under a single identifier. It functions akin to a record in alternative coding languages and serves the purpose of modeling real-life entities with diverse attributes. One key benefit of a structure compared to an array is its capability to accommodate variables of different types, unlike an array which is restricted to elements of the same data type.
It enhances its capacity to manage intricate data. Every variable inside a structure is known as a member, and it can be retrieved by utilizing the structure's name along with the dot operator. Memory is allocated for a structure only when an object of it is instantiated. After instantiation, all its members are positioned in contiguous memory addresses for efficient retrieval.
C++ structures can include the following:
- Data Members: These are the many sorts of variables grouped together within the structure.
- Member Functions: In C++, structures, such as classes, can have functions that allow for the encapsulation of data behaviour.
Syntax
It has the following syntax:
struct StructureName
{
// Data Members
DataType member1;
DataType member2;
// ...
DataType memberN;
// Optional Member Functions
ReturnType functionName()
{
// Function Body
}
};
Parameters
- Struct: The "struct" keyword defines a structure.
- StructureName: The name given to the structure type. It serves as a blueprint for the creation of structural variables (instances).
- Data Members: These are variables specified within the structure that can be of any data type.
- Member Functions (Optional): Like class methods, C++ structures can include functions that operate on data members.
C++ Structure Example
Let's consider an example to demonstrate the syntax in C++.
Example
#include <iostream>
using namespace std; //using standard namespace
struct Student
{
int roll_number;
string name;
float marks;
void display()
{
cout << "The name of the student is: " << name << endl;
cout << "The Roll Number of a student is: " << roll_number << endl;
cout << "Marks of the student is: " << marks << endl;
}
};
int main() //main function
{
Student s = {1, "Joseph", 95.5};
s.display();
return 0;
}
Output:
The name of the student is: Joseph
The Roll Number of a student is: 1
Marks of the student is: 95.5
Explanation:
In this instance, a Student construct is utilized to hold information such as the student's identification number, name, and academic scores. Additionally, it incorporates a display method to showcase this data. Within the main function, a Student instance is created with specific data values, followed by invoking the display method to exhibit the stored information.
What is a C++ Class?
In C++, a class represents a user-defined data type used as a template for creating objects. It consists of data members (attributes) and member functions (methods) that define the characteristics and behavior of the object.
For instance, let's take the class Dog as an example. Each dog within this class can vary in terms of breed and color, yet they all exhibit common traits like species and typical behavior. The class establishes these shared properties, with each unique object within the class representing a specific dog.
Syntax
It has the following syntax:
class ClassName
{
private:
// Private data members
DataType member1;
DataType member2;
public:
// Public member functions
ReturnType function1();
ReturnType function2();
};
Parameters
- class: A class is defined with the term "class".
- ClassName: The class's identifier or name is ClassName.
- Private data members: Private members can only be accessed within the class.
- Public functions: Public functions enable controlled access to the class's internal members.
- Member functions: Member functions define the operations that can be performed on the class data.
C++ Class Example
Let's consider an example to demonstrate the concept of classes in C++.
Example
#include <iostream>
using namespace std; //using standard namespace
class Car
{
private:
string brand;
int year;
public:
void display(string br, int yr)
{
brand = br;
year = yr;
}
void display()
{
cout << "The brand name is: " << brand << "\nThe launch year is: " << year << endl;
}
};
int main() //main function
{
Car c;
c.display("Toyota", 2020);
c.display();
return 0;
}
Output:
The brand name is: Toyota
The launch year is: 2020
Explanation:
In this instance, we are examining a scenario where a class named Car contains two member methods sharing identical names: one function assigns the brand and year of the car, whereas the other function outputs this information. Within the main function, an instance c is instantiated, its attributes are set, and subsequently, the stored details are showcased.
Similarities between Structure and Class in C++:
While structures and classes are utilized in different manners within C++, they possess numerous core similarities stemming from the language's object-oriented nature. Below are the primary resemblances that highlight the close relationship between these two custom data types:
In C++, both structures and classes are defined with identical fundamental syntax. The sole distinction lies in the default access modifier, which is public for structures and private for classes.
When creating a structure or a class, the name can serve as a data type for producing variables or instances. For instance, both Student (defined as a struct) and Employee (defined as a class) can be employed to instantiate objects similarly to how standard types are utilized.
Both structures and classes support access specifiers such as public, private, and protected. This indicates that structures are inherently public, though they can also contain private members similar to classes.
Structures and classes both offer inheritance, a crucial feature in object-oriented programming. Inheritance enables the derivation of one structure or class from another, facilitating reusability and the creation of hierarchical structures.
C++ structures, like classes, are capable of containing constructors, destructors, and member functions. This functionality allows structures to behave in a manner akin to classes with regards to object initialization and behavior.
Key Differences between Structure and Class in C++
The following table outlines the primary variances between Structure and Class in C++:
| Aspect | Structure | Class |
|---|---|---|
| Default Access Modifier | Members are public by default. | Members are private by default. |
| Access Specifier Behavior | Structures expose their data by default, which means no encapsulation unless specified. | Classes encourage encapsulation by hiding data unless access is explicitly granted. |
| Declaration Keyword | Declared using the "struct" keyword. | Declared using the "class" keyword. |
| Purpose | It is mainly used to group related variables of different types. | It is mainly used for data abstraction, inheritance, and object-oriented design. |
| Syntax | struct StructName { member1; member2; }; | class ClassName { member1; member2; }; |
| Instance Name | A structure instance is often referred to as a structure variable. | A class instance is known as an object. |
| Default Initialization | Structure members are not automatically initialized unless initialized explicitly or via a constructor. | Requires constructors to initialize members. |
| Support for Destructor | In C++, structures do support destructors just like classes. | It supports both constructors and destructors. |
| Null Values | Structures can have pointers, and pointers can hold null. | Null values are allowed in class pointers. |
| Inheritance and Polymorphism | In C++, structures fully support inheritance and polymorphism like classes. | It fully supports inheritance and polymorphism. |
| Constructor and Destructor | Structures can have constructors and destructors, but not by default. | Classes support user-defined constructors and destructors explicitly. |
| Encapsulation Level | Low encapsulation, since all members are public by default. | High encapsulation, supporting data hiding, and access control. |
| Type Behavior | It is considered a value type copied by value. | It is considered a reference type accessed by reference. |
| Use Case | It is preferred in small programs or data grouping tasks. | It is preferred in large, object-oriented software systems. |
Conclusion
In summary, C++ employs a structure to efficiently group basic data with minimal memory usage due to its nature as a value type that is user-friendly. When dealing with complex operations, it is advisable to opt for a class as it offers enhanced data protection, supports inheritance, and functions as a reference type. While structures are suitable for straightforward tasks, classes offer greater manageability and adaptability in extensive systems.
Difference between Structure and Class in C++ MCQS
1) What is the default access modifier for a C++ structure?
- Private
- Protected
- Public
- Internal
2) In C++, what keyword is used to declare a class?
- struct
- typedef
- enum
- class
3) In C++, which of the following accepts constructors and destructors?
- Only classes
- Only structures
- Both structures and classes
- Neither
4) Which of the following holds true for C++ structures?
- Support inheritance
- Typically used for grouping relevant data
- Are reference types
- Members are private by default
5) Where are structure variables stored when declared as local variables?
- Stack
- Register
- Heap
- Cache