When to Use Structs Instead of Classes in C++?

  • C/C++
  • Thread starter Math Is Hard
  • Start date
  • Tags
    C++ Classes
In summary, the main difference between structs and classes in C++ is the default visibility of their members (public for structs and private for classes). Structs are mainly used in C++ for backward compatibility with C and are generally not used by most C++ programmers. They can be used for classes where all members are public, but this is usually a matter of preference. Data structures and data types are often used interchangeably and refer to aggregations of multiple variables, but the distinction is primarily in their context and syntax. Some programmers choose to use structs for simpler classes, while others prefer to use classes with public members. Ultimately, it comes down to personal preference and the needs of the specific program or project.
  • #1
Math Is Hard
Staff Emeritus
Science Advisor
Gold Member
4,652
37
I was trying to understand how structs differ from classes in c++ and I came across this:
http://carcino.gen.nz/tech/cpp/struct_vs_class.php
The only difference between structs and classes in C++ is that the members of a struct have public visibility by default, and the members of a class have private visibility by default.

I was wondering.. when would you choose to use a struct in c++ rather than a class?
 
Last edited by a moderator:
Technology news on Phys.org
  • #2
Structs are really hold-overs from C, the predecessor of C++. Structs still exist in the C++ language mainly just to keep it backward-compatible with C. You won't find many C++ programmers using structs in C++.

- Warren
 
  • #3
thanks, Warren. There was a chapter on structs in my book, but we never covered them, so I couldn't understand what that was all about. We stopped just before that and started learning classes.

One other thing I am confused about is why an array is called a data structure, but a structure (struct) is called a data type. They both seem to have elements that are organized in a certain way.
 
Last edited:
  • #4
The terms "data structure" and "data type" are certainly thrown around a bit sloppily, and sometimes are even used somewhat interchangably. A lot of the distinction is in their context.

All variables in C have a specific data type. For example, "char c" declares a new variable, named 'c,' of type char. A data type can be a primitive type, provided by the compiler (e.g. int, char, float, double), or they can be user-defined and may contain numerous internal fields. Classes and structs are syntactical mechanisms used to define new types.

"Data structures," on the other hands, are aggregations of multiple variables, of potentially different types. An array is a "data structure," because it contains many elements of the same type.

Here are some examples of the ambiguity:

Code:
struct foo {
    char c[10];
}

struct foo myFoo;

myFoo.c[0] = 0;

In this case, "foo" would be referred to by most programmers as a type, though it really contains nothing more than an array of characters.

Code:
typedef char bar;

bar myBar[10];

myBar[0] = 0;

In this case, bar would be referred to as a type, but myBar would be referred to as a data structure.

These two "approaches" would allocate the same memory, and behave essentially the same way -- in fact, both programs would probably produce identical machine code under many compilers.

The only difference, the reason why people call foo a data type and myBar a data structure, is the syntax used for each. foo is declared in such a way that suggests it is meant to be used as a type -- it internalizes the array. myBar is declared in such a way that it is meant to be used as a data structure, exposing the array directly.

- Warren
 
Last edited:
  • #5
you will use structs for classes which every member is public.
In most of the 3D engines that I have taken apart, they apply this to the math classes that are used a lot like vectors: struct { x,y,z }, and simple geometries like lines and planes as well as to teh colour class struct {r,g,b}. Note that I did not actually use the correct syntax, iwas just providing examples. Sometimes people like to leave certain math functions as global namespace functions. Like Distance & Intersection and implement old C style structs where there are no member functions with teh struct. Others like to have complete access to the struct but still include the functions as member functions rather than global scope functions. I have been through various phases of a simple 3D engine to see what the difference between pure C(functional), C/C++ mix, pure OO. I still don't know what the difference is besides convenience in Coding. So I stick with the middle Blending both Functional & OO. with C++ compilers you can do a lot of function/operator overload in the global namespace, so i get the best of both worlds. Use OO for more complicated classes like A Renderer, DataStructures, EngineApp, SceneManagement stuff. And use mostly functional programming for all the math aspects.
 
  • #6
neurocomp:

There is no specific reason why those programmers used the keyword "struct," except for perhaps historical reasons or for nostalgia. Many programmers associate "struct" with C structs, which no longer actually exist in C++. In C++ terms, a C struct is just a degenerate class with nothing but member variables.

- Warren
 
  • #7
Chroot: how does a DS potentially different types? Are you referring to polymorphism in which case thers a common base type? Never seen anyone describe DS with these words before "aggregations of multiple variables" cool.
 
  • #8
chroot said:
The only difference, the reason why people call foo a data type and myBar a data structure, is the syntax used for each. foo is declared in such a way that suggests it is meant to be used as a type -- it internalizes the array. myBar is declared in such a way that it is meant to be used as a data structure, exposing the array directly.
ah! I think I am starting to see the light. Thanks!
 
  • #9
neurocomp2003 said:
you will use structs for classes which every member is public.
Is this better than using a class and making all its members public? sorry if that's a naive question.
 
  • #10
chroot: from what I've seen of the C++struct use, people do this

struct SVector {
REAL x,y,z;
Add(SVector x);
operator(SVector v);
};
struct SLine {
SVector p, v;
REAL Dist(SVector);
};
Which is not C structs, because you can't have function members in C struct or to my knowledge(though you can have function pointers) You are probably right in what you have said about the nostalgia thing. I wouldn't know becuase I've only begun coding these past 2 years in C++.
 
  • #11
MathIsHard: wouldn't know...the syntax differs only by
struct StructName {};
class ClassName { /*no code above this public*/ public: ...};

You can inherit from both.
 
  • #12
neurocomp2003 said:
MathIsHard: wouldn't know...the syntax differs only by
struct StructName {};
class ClassName { /*no code above this public*/ public: ...};

You can inherit from both.
ok, guess it is just a matter of preference then. thanks.
 
  • #13
Edit: update - I was thinking C structures, not C++ structures. The text you quoted is correct, the only difference is the default of public or private for the members.

Original text:
As previously mentioned, classes can have functions as members. They also have two automatic functions, one for creation, and one for deletion.

With structures, you have to use pointer to functions to get the equivalent.

Structure members can't be over ridden with new names or members, but class member can be. For example there is a windows class that provides member functions for all the windows message types, and a programmer overrides a sub-set of these by declaring functions to handle some of the message types in his code.
 
Last edited:
  • #14
Jeff,

Everything you said is, in fact, wrong. Try compiling the following program with a C++ compiler:

Code:
#include <iostream>

using namespace std;

struct foo {
	foo();
	virtual void bar();
};

foo::foo() {
	cout << "Structs can have ctors." << endl;
}

void foo::bar() {
	cout << "Structs can have member methods." << endl;
}

struct foo_child : foo {
	void bar();
};

void foo_child::bar() {
	cout << "Structs can even have inheritance." << endl;
}

int  main(void) {
	foo f;
	f.bar();
	
	foo_child fc;
	fc.bar();
	
	return 0;
}

- Warren
 
  • #15
I was trying to compare C structures versus C++ classes. In the case of C++ structures, you're correct, there isn't a lot of difference.

Normally I define structures with typedefs, using leading underscores for the struct, and no leading underscore for the typedef (Microsoft standard).

typedef struct _EXAMPLE{
...
}EXAMPLE, *PEXAMPLE;

Curious about this, do non-Microsoft compliers allow struct reference within stuctures?
For example, this case for usage with a single linked list of structures:

typedef struct _EXAMPLE{
struct _EXAMPLE *pNext;
...
}EXAMPLE, *PEXAMPLE;
 
Last edited:
  • #16
Jeff Reid said:
I meant structures as in C structures, not C++.
As per the title, this thread is about structs in C++.

- Warren
 
  • #17
Math Is Hard said:
I was wondering.. when would you choose to use a struct in c++ rather than a class?
Based on the quoted text, use a struct when most or all of the members will be public, and classes when not. ... or you could just use classes and declare everything public manually.
 
  • #18
chroot said:
As per the title, this thread is about structs in C++.
I updated my response to reflect this. Wasn't paying attention, and at work a lot of applications are a mix of C and C++ programs.
 
  • #19
jeff Reid: "when most or all of the members will be public" ...its all not most. any member of a struct in C++ is always public.
 
  • #20
neurocomp2003 said:
any member of a struct in C++ is always public.
unless you make it private. :smile:
 
  • #21
heh I learned something new today...thought there were compiler errors for having private & protected in structs. But I guess there aren't
 
  • #22
I was wondering.. when would you choose to use a struct in c++ rather than a class?

There's no hard and fast rule. Projects sometimes impose their own rules.

Left to myself, when I simply want to aggregate some public data I use a struct; when I want data to be hidden behind an interface I use a class.

Tim
 
  • #23
I have a great example of when you're making a Blackjack game.
First you want to make a struct CARD, which just contains the card number, and the color(hearts, diamonds, ..).
And then you want to make a class which can be used as a deck, or a hand. It would consist of a vector of the struct CARD, and also members like shuffleDeck, getCard etc..

I hope someone found this helpful,
Diamondz
 
  • #24
nmtim said:
There's no hard and fast rule. Projects sometimes impose their own rules.
Several projects, include the one I am working on, solve this problem in a very simple way: struct is a verboten keyword.
 

1. What is the difference between a struct and a class in C++?

A struct is a user-defined data type that can contain both data members and member functions, similar to a class. However, in a struct, all members are public by default while in a class, members are private by default. Additionally, structs are commonly used for data storage and manipulation while classes are used for encapsulating data and behavior.

2. How do you declare a struct or class in C++?

To declare a struct or class in C++, you use the struct or class keyword, followed by the name of the struct or class. For example, struct Student or class Rectangle. This creates a blueprint for the struct or class, but does not allocate any memory.

3. Can a struct or class have constructors and destructors in C++?

Yes, both structs and classes can have constructors and destructors in C++. Constructors are used to initialize the data members of a struct or class when an object is created, while destructors are used to clean up any resources allocated by the object when it is destroyed. Constructors have the same name as the struct or class, while destructors have the same name preceded by a tilde ~.

4. How do you access the data members and member functions of a struct or class in C++?

To access the data members and member functions of a struct or class in C++, you use the dot operator . between the object name and the member name. For example, myStudent.name = "John"; or myRectangle.calculateArea();. If the data member or member function is private, you can use public member functions to access or modify the data.

5. Can a struct or class inherit from another struct or class in C++?

Yes, C++ supports both single and multiple inheritance, where a struct or class can inherit data members and member functions from another struct or class. This allows for code reuse and the creation of more complex data structures. However, care should be taken when using multiple inheritance to prevent potential issues such as the diamond problem.

Similar threads

  • Programming and Computer Science
Replies
16
Views
3K
  • Programming and Computer Science
Replies
8
Views
1K
  • Programming and Computer Science
Replies
6
Views
921
  • Programming and Computer Science
Replies
11
Views
2K
  • Programming and Computer Science
2
Replies
52
Views
3K
  • Programming and Computer Science
Replies
30
Views
2K
  • Programming and Computer Science
2
Replies
36
Views
2K
  • Programming and Computer Science
Replies
8
Views
3K
  • Programming and Computer Science
2
Replies
35
Views
2K
  • Programming and Computer Science
2
Replies
36
Views
2K
Back
Top