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

 Live Demo

#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.

Updated on: 26-Jun-2020

299 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements