Structure vs class

Posted by Bartosz Stempień on August 30, 2019 · 2 mins read

Hello everyone,
today post will be the shortest one so far. We will talk about differences between structure and class.
This topic isn’t hard but beginners programmers in C++ can have some thoughts about it.

It’s a common, good convention to use structure only for data without any methods, constructors or destructor. Just only data. This is the first difference.
Of coure structure have methods and even constructor or destructor. Structures are avalaible in C++ to keep backward compatibility with C.

The second difference is that members of a class are private by default, in structure there are public.

The third difference. The default visibility of structure is public, the class is private. It means also, if you don’t specify anything then the struct will inherit publicly from its base class:

struct T : Base // struct T : public Base
{
   ...
};

class T : Base // class T : private Base
{
   ...
};

There are no more differences between structure and class in C++.
To prove it, we will look at that code:

#include <type_traits>
#include <iostream>

int main()
{
    struct Str {};
    
    std::cout << std::is_class<Str>::value; //1 
}

There you can read more about type traits