Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I use structs in C++?

The difference between struct and class is small in C++, basically only that struct members are per default public and class members are per default private.

However, I still use structs whenever I need pure data structures, for instance:

struct Rectangle {
    int width;
    int height;
};

I find that very convenient to work with:

Rectangle r;
r.width = 20;
r.height = 10;

However, data structures are from procedural programming, and I'm doing object oriented programming. Is it a bad idea to introduce this concept into OO?

like image 600
forceal Avatar asked Sep 28 '10 15:09

forceal


People also ask

When should you use structs?

Structs should be used to represent a single value because structs are value types, like a number. The number '5' is an int, which is a value type, which makes sense because every 5 is a 5. It wouldn't make sense to have an instance of 5; A single 5 is no-different than any other 5.

Are structs better than classes?

There is no difference between classes and structs. Structs are classes; only default access is flipped from private to public.

Why do we use structs in C?

Structures (also called structs) are a way to group several related variables into one place. Each variable in the structure is known as a member of the structure. Unlike an array, a structure can contain many different data types (int, float, char, etc.).

When should I use a struct instead of a class?

Class instances each have an identity and are passed by reference, while structs are handled and mutated as values. Basically, if we want all of the changes that are made to a given object to be applied the same instance, then we should use a class — otherwise a struct will most likely be a more appropriate choice.


2 Answers

No. If it makes sense to use a struct somewhere, why would you complicate things using something else that isn't meant to fit the purpose ?

In my projects, I tend to use struct for simple "structures" which just need to hold some trivial data.

If a data structure needs to have some "smartness" and hidden fields/methods, then it becomes a class.

like image 191
ereOn Avatar answered Sep 28 '22 07:09

ereOn


structs are especially useful for POD (plain old data) encapsulation. There is a lot more on this at struct vs class in C++

like image 28
Steve Townsend Avatar answered Sep 28 '22 09:09

Steve Townsend