C++ Class Vs Struct
The basic functionality of struct and class is the same. The only difference between them is the difference in how they access their member variables and methods by default.
In the case of struct, the default accessibility is public, while in the case of class it is private.
Hence, because of that reason, you can see that from the below example Code1 fails while Code2 runs perfectly fine.
Additionally, Classes can contain functions and we call them methods. Struct in its basic form,
Code1:
#include "iostream"
using namespace std;
class Test {
// x is private (as we know that in a class by default accessibility //is Private)
int x;
};
int main()
{
Test t;
t.x = 20; // compiler error because x is private
return t.x;
}
Output:
Code2:
#include "iostream"
struct Test {
// x is public (as we know that in a struct by default accessibility //is Public)
int x;
};
int main()
{
Test t;
t.x = 20;
// works fine because x is public
std::cout << t.x;
}
Output:
20