In C++, technically, the difference between the struct and class is that the struct is public by default and the class is private. Generally, we use the struct to carry the data. See the below comparison chart for struct and class,
Structure
Class
By default member variables and methods of the struct is public.
By default member variables and methods of the class is private.
When deriving a struct, the default access specifier is public.
When deriving a class, default access specifiers are private.
Let see two example codes to understand the difference between struct and class.
Example-1:
#include <iostream>
using namespace std;
class Test
{
int x; // Default: x is private
};
int main()
{
Test t;
t.x = 20; // compiler error because x is private
return 0;
}
Output: error: ‘int Test::x’ is private|
Example-2:
#include <iostream>
using namespace std;
struct Test
{
int x; // Default: x is public
};
int main()
{
Test t;
t.x = 20; // No compiler error because x is public
cout << t.x;
return 0;
}
In C++, technically, the difference between the struct and class is that the struct is public by default and the class is private. Generally, we use the struct to carry the data. See the below comparison chart for struct and class,
StructureClasspublic.private.public.private.Let see two example codes to understand the difference between struct and class.
Example-1:
Output: error: ‘int Test::x’ is private|
Example-2:
Output: 20
need an explanation for this answer? contact us directly to get an explanation for this answer