Is there any advantage over using a class over a struct in cases such as these? (note: it will only hold variables, there will never be functions)
class Foo {
private:
struct Pos { int x, y, z };
public:
Pos Position;
};
Versus:
struct Foo {
struct Pos { int x, y, z } Pos;
};
Similar questions:
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.
Unlike class, struct is created on stack. So, it is faster to instantiate (and destroy) a struct than a class. Unless (as Adam Robinson pointed out) struct is a class member in which case it is allocated in heap, along with everything else.
The major difference like class provides the flexibility of combining data and methods (functions ) and it provides the re-usability called inheritance. Struct should typically be used for grouping data. The technical difference comes down to subtle issues about default visibility of members.
There is no real advantage of using one over the other, in c++, the only difference between a struct and a class is the default visibility of it's members (structs default to public, classes default to private).
Personally, I tend to prefer structs for POD types and use classes for everything else.
EDIT: litb made a good point in the comment so I'm going to quote him here:
one important other difference is that structs derive from other classes/struct public by default, while classes derive privately by default.
One side point is that structs are often used for aggregate initialized data structures, since all non-static data members must be public anyway (C++03, 8.5.1/1).
struct A { // (valid)
{
int a;
int b;
} x = { 1, 2 };
struct A { // (invalid)
private:
int a;
int b;
} x = { 1, 2 };
class A { // (invalid)
int a;
int b;
} x = { 1, 2 };
class A { // (valid)
public:
int a;
int b;
} x = { 1, 2 };
class A { // (invalid)
public:
int a;
private:
int b;
} x = { 1, 2 };
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With