C++ is an object-oriented programming language that values data and how it is managed. It encourages modular programming by allowing developers to partition memory into different parts for data and functions. Both structures and classes in C++ allow for the creation of custom data types that can then be used to create instances or objects.
Both structures and classes are similar in many aspects, but they differ significantly in their operation. Before exploring these differences, it's helpful to understand the fundamental ideas of C++ structures and classes.
What is Structure in C++?
In C++, a structure is a user-defined data type that allows variables of different types to be grouped under a common name. It works similarly to a record in other programming languages and can be used to represent real-world entities with several properties. A structure has a fundamental advantage over an array in that it can include variables of multiple types, whereas an array only keeps elements of the same data type .
It improves its ability to handle more complex data. Each variable within a structure is referred to as a member, and it may be accessed using the structure's name and the dot operator. A structure only uses memory when an instance of it is created. Once formed, all of its members are stored in nearby memory locations to enable quick access.
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 us take an example to illustrate the structure 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 example, we have taken a Student structure that stores a student's roll number, name, and marks, and it has a display function to print them. In the main function, a Student object is initialized with values before calling the display function to display the data.
What is a C++ Class?
In C++, a class is a data type that is defined by the user and serves as a blueprint for object creation. It has data members (attributes) and member functions (methods) that determine the behaviour and state of the object.
For example, Consider the class Dog, and each dog may differ in breed and colour, but they all share common characteristics such as species and general behavior. These shared attributes are defined by the class, while individual class objects represent specific dogs.
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 us take an example to illustrate the class 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 example, we have taken a class Car has two member functions with the same name: one sets the car's brand and year, while the other prints them. The main function creates an object c, initializes its data, and then displays the stored information.
Similarities between Structure and Class in C++:
Although structures and classes are frequently employed in various ways in C++, they share many fundamental traits due to the language's object-oriented design. The following are the main similarities that show how closely related these two user-defined types are:
In C++, both structures and classes are declared using the same basic syntax. The only syntax change is the default access modifier, which is public for structures and private for classes.
Whether we construct a structure or a class, its name can be used as a data type to generate variables or objects. For example, both Student (a struct) and Employee (a class) can be used to define instances in the same way that built-in types are.
Both structures and classes allow access specifiers like public, private, and protected. It means that structures are public by default, but they can also include private members, just like classes.
Structures and classes both provide inheritance, which is an important element of object-oriented programming. We can derive one structure or class from another, which allows for reusability and hierarchical architecture.
C++ structures, such as classes, can have constructors, destructors, and member functions. It enables structures to act similarly to classes in terms of object initialization and behaviour.
Key Differences between Structure and Class in C++
The table below summarises all of the fundamental differences 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 conclusion, C++ utilize a structure for simple data grouping with low memory requirements because it is a value type that is simple to use. When working with more complicated logic, consider using a class because it provides better data security, permits inheritance, and is a reference type. Structures can be useful for simple tasks, but classes provide more control and flexibility in larger 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