I have been reading Qt Creator's source code.
When is using a struct more appropriate than using a class in C++?
4 Answers
It is purely a matter of personal preference or coding conventions. struct and class are essentially the same in C++, with the difference being the default access specifiers and base classes being public for a struct and private for a class.
For example, here two definitions of Bar are equivalent:
class Foo {};
struct Bar : Foo {};
class Bar : public Foo {};
Here too:
class Foo {};
struct Bar : private Foo {};
class Bar : Foo {};
and here too:
class Bar
{
int n; // private
public:
double x; // public
};
struct Bar
{
private:
int n;
public:
double x;
};
Furthermore, you could forward declare Bar as class Bar or struct Bar interchangeably.
- 223,364
- 34
- 402
- 480
There's no difference aside from default access (struct => public, class => private). For readability, I prefer using struct when I'm defining a plain-old C struct (just data), or when the majority of my members/methods are public.
- 7,746
- 1
- 26
- 39
I think of struct as a record. They bundle together variables and you want to access and modify struct members without indirection, such as a function call. For example, when you want to write together groups of data items to dump them into a file or send them over network then using class may even make the code harder to read and understand.
- 94,503
- 21
- 155
- 181
It might be more suitable when it's Plain Old Data without any functionality on it. In C++, the only difference between class and struct is that struct members are public by default, as opposed to private for class.
- 126,289
- 21
- 250
- 231