Structure vs Class in C++



In C++ the structure and class are basically the same. But there are some minor differences. These differences are like below.

The class members are private by default, but members of structures are public. Let us see these two codes to see the differences.

Example Code for Class

Here is the following code for the class.

Open Compiler
#include using namespace std; class my_class { public: int x = 10; }; int main() { my_class my_ob; cout Output 10 Example Code for Structure Here is the following code for a structure. #include using namespace std; struct my_struct{ int x = 10; }; int main() { my_struct my_ob; cout Output 10 When we derive a structure from a class or structure, the default access specifier of that base class is public, but when we derive a class the default access specifier is private. Example Code 1 #include using namespace std; class my_base_class { public: int x = 10; }; class my_derived_class : my_base_class{ }; int main() { my_derived_class d; cout Output This program will not be compiled. It will generate a compile time error that the variable x of the base class is inaccessible Example Code 2 #include using namespace std; class my_base_class { public: int x = 10; }; struct my_derived_struct : my_base_class{ }; int main() { my_derived_struct d; cout Output 10
Updated on: 2024-12-03T09:42:07+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements