Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it always evil to have a struct with methods?

Tags:

c++

class

struct

I've just been browsing and spotted the following...

When should you use a class vs a struct in C++?

The consensus there is that, by convention, you should only use struct for POD, no methods, etc.

I've always felt that some types were naturally structs rather than classes, yet could still have a few helper functions as members. The struct should still be POD by most of the usual rules - in particular it must be safe to copy using memcpy. It must have all member data public. But it still makes sense to me to have helper functions as members. I wouldn't even necessarily object to a private method, though I don't recall ever doing this myself. And although it breaks the normal POD rules, I wouldn't object to a struct having constructors, provided they were just initialise-a-few-fields constructors (overriding assignment or destructors would definitely be against the rules).

To me a struct is intuitively a collection of fields - a data structure node or whatever - whereas a class is an abstraction. The logical place to put the helper functions for your collection-of-fields may well be within the struct.

I even think I once read some advice along these lines, though I don't remember where.

Is this against accepted best practice?

EDIT - POD (Plain Old Data) is misrepresented by this question. In particular, a struct can be non-POD purely because a member is non-POD - e.g. an aggregate with a member of type std::string. That aggregate must not be copied with memcpy. In case of confusion, see here.


1 Answers

For what it's worth, all the standard STL functors are defined as structs, and their sole purpose is to have member functions; STL functors aren't supposed to have state.

EDIT: Personally, I use struct whenever a class has all public members. It matters little, so long as one is consistent.

like image 63
2 revsBilly ONeal Avatar answered Sep 14 '25 16:09

2 revsBilly ONeal