Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Class vs Struct for data only?

Tags:

c++

class

struct

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:

  • When should you use a class vs a struct in C++?
  • What are the differences between struct and class in C++?
  • When should I use a struct instead of a class?
like image 840
Daniel Sloof Avatar asked Jan 10 '09 17:01

Daniel Sloof


People also ask

Is it better to use struct or 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.

Are structs more efficient than classes?

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.

Why do we use class instead of structure?

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.


2 Answers

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.

like image 68
Evan Teran Avatar answered Sep 21 '22 09:09

Evan Teran


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 };
like image 41
Roger Nelson Avatar answered Sep 23 '22 09:09

Roger Nelson