Q:

What are the differences between a class and a structure in C++?

0

What are the differences between a class and a structure in C++?

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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;
}

Output: 20

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

C++ Interview Questions and Answers(2022)

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Why is the size of an empty class not zero in C++?... >>
<< What are C++ access modifiers?...