

- 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
When should you use a class vs a struct in C++?
Structures and classes are very similar in C++ except for some differences. So details about these differences are given below that help to decide when to use a class or structure in C++.
Differences between Class and Structure
All the members of a class are private by default. This is different compared to structures as all the members of a structure are public by default.
A program that demonstrates a class in C++ is given as follows −
Example
#include <iostream> using namespace std; class Example { int val; }; int main() { Example obj; obj.val = 20; return 0; }
This program results in an error as val is private by default and so cannot be accessed directly using obj.
A program that demonstrates a structure in C++ is given as follows −
Example
#include <iostream> using namespace std; struct Example { int val; }; int main() { Example obj; obj.val = 20; cout<<"Value is: "<<obj.val; return 0; }
Output
The output of the above program is as follows −
Value is: 20
The above program works correctly as val is public by default and so can be accessed directly using obj.
Another difference between a class and a structure is evident during inheritance. When inheriting a class, the access specifier of the base class is private by default. Comparatively, when inheriting a structure, the access specifier of the base structure is public by default.
- Related Questions & Answers
- C/C++ Struct vs Class
- When should you use sets in Javascript?
- When should you use 'friend' in C++?
- When you should not use JavaScript Arrow Functions?
- When should I use the keyword ‘this’ in a Java class?
- When should I use a composite index in MySQL?
- When to use references vs. pointers in C/C++
- When should we create a user-defined exception class in Java?
- What is a smart pointer and when should I use it in C++?
- When Should I use Selenium Grid?
- Why you should use a VPN on Public Wi-Fi?
- When should I use a semicolon after curly braces in JavaScript?
- What are the differences between a class and struct in C#?
- When should I use MySQL compressed protocol?
- When to use new operator in C++ and when it should not be used?