Difference Between Structure and Class in C++
The table given below shows the difference between structure and class in C++. In this table, the difference between structure and class in C++ is based on the keyword used to define, by default the data member, security, etc. It is an essential topic of the GATE CSE syllabus.
Key Difference Between Structure and Class in C++
Structure | Class |
The data member of the class is public by default. | The data member of the class is private by default. |
The structure is defined by using the ‘struct’ keyword. | The ‘class’ keyword is used to define the class in C. |
The structure is used in small programs like storing the student’s five subject marks. | Class is used in the large program like inheritance, polymorphism, and OOPs concept. |
The structure cannot be inherited. | The class can be inherited. |
The structure is the collection of data members (variables). | Class is the collection of member functions and data members. |
The structure does not provide security. | The class provides high security. |
What is a class in C++?
Before knowing the difference between structure and class in C++, let us understand class in C++. A class in C++ represents the group of similar objects which holds its own data member and member function together.
The syntax of class in C++ is as follows:
class Class_name
{
Access modifiers;
Data members;
Member functions()
{
//body
}
};
The access modifier is of three types that are as follows:
- Private: The private members can only be accessed from within the class.
- Public: The public members can be accessed from within as well as outside the class.
- Protected: The protected members can be accessed from within as well as outside the class with the help of the friend function.
What is Structure?
Before knowing the difference between structure and class in C++, let us understand structures. Structures are the user-defined data types that allow you to combine data items of different kinds. A structure in C++ is a group of data elements grouped together under one name. These data elements, known as members, can have different types and lengths.
The structure is the way to group the variables. The structure in C++ contains two types of members that are as follows:
- Data variables
- Member functions
The syntax of structure in C++ is as follows:
Struct Structure_name
{
Member 1;
Member 2;
}
Further, check out some important related topics:
Comments
write a comment