

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
#include <iostream> using namespace std; class my_class { int x = 10; }; int main() { my_class my_ob; cout << my_ob.x; }
Output
This program will not be compiled. It will generate compile time error for the private data member.
Example Code
#include <iostream> using namespace std; struct my_struct{ int x = 10; }; int main() { my_struct my_ob; cout << my_ob.x; }
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 deriving a class the default access specifier is private.
Example Code
#include <iostream> 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 << d.x; }
Output
This program will not be compiled. It will generate compile time error that the variable x of the base class is inaccessible
Example Code
#include <iostream> 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 << d.x; }
Output
10
- Related Questions & Answers
- Target Capital Structure Vs. Optimum Capital Structure
- Rooted vs Unrooted Trees in Data Structure
- Debug Class vs Debugger Class in C#
- Abstract vs Sealed Classes vs Class Members in C#
- Difference Between Structure and Class
- C/C++ Struct vs Class
- Difference between Class and Structure in C#
- Class method vs static method in Python
- Functional Components Vs. Class Components in ReactJS
- Push vs pop in stack class in C#
- STL Priority Queue for Structure or Class in C++
- Object level lock vs Class level lock in Java?
- When should you use a class vs a struct in C++?
- What are the differences between a class and a structure in C#?
- Virtual vs Sealed vs New vs Abstract in C#
Advertisements