views:

417

answers:

10

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?

+18  A: 

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.

ereOn
In fact, used consistently this way, `struct` reliably tells readers "I am a dumb data structure".
Péter Török
A struct with no modifiers or methods is sometimes referred to as a [POD](http://stackoverflow.com/questions/146452/what-are-pod-types-in-c) struct. They are often used as a backwards compatible interface with C libraries as it is (supposedly) guaranteed to be laid out as though it were a C struct. The other main difference to account for when using structs vs. classes is that the default visibility of members within a struct is public rather than private.
LBushkin
Your struct won't have a constructor or destructor. This may be a performance improvement over classes.
phkahler
@phkahler, structs will have a default constructor just like classes.
Winston Ewert
So a C++ struct takes more memory than a C struct? Always?
phkahler
@phkahler: I guess there is some misunderstanding here. Whatever the count of methods in a class or a struct, it **won't grow** ! Only the variables will make it grow.
ereOn
@phkahler: If you define *the same* struct in C and C++, its size and layout will be the same.
jalf
If you can do polymorphism there must be some type dependent information stored *in the object* which does not occur in a plain old C struct. Hence my question and the "Always?" that followed.
phkahler
@phkahler: Polymorphism is a different matter. And as long as we talk about single classes or structures (without inheritance), methods are just special functions with an hidden parameter; and they do not occupy any single byte in the class instances.
ereOn
+3  A: 

In my opinion, no, this is not a bad idea. If you're going to use a class in the same fashion, like

class Rectangle {
    public:
        int width;
        int height;
};

then you may as well use a struct. This will help make sure you're not forgetting to declare anything public, and if you keep it consistent, then future developers (including future you) will know that you intended this purely as a data object, not something to have methods within.

It's still pretty much an object from all usability perspectives, so no, it doesn't conflict with OO design.

Slokun
OT: it's not valid C++ code snippet
erjot
He just needs to edit it, and put a colon (:) after the public declarations.
C Johnson
@erjot heh, thanks, been a couple years since I last actually did any C++, been doing mostly Java, PHP and C#, easy to forget syntax differences.
Slokun
+1  A: 

If your application needs it, use it. If your design requires you to have just public members you can use struct itself...

liaK
+1  A: 

I use structs all the time for objects like unary_function and such. There's really no point in having to explicitly declare public on a class with only an operator() method. Furthermore, it's not like you're inviting it to be inherited.

wheaties
A: 

I would prefer struct-like class. The first reason is to avoid uninitialized struct. The other reason is that you will be always able to add any convenience methods to the struct if wanted.

tia
It is just as easy to fail to init a `class` as a `struct`.
Steve Townsend
You can add convenience methods to `struct` as well. I don't exactly see your point.
ereOn
@Steve: How about default constructor? From the example, I think we could use it to set width and height to 0.
tia
@ereOn: Technically correct, but if I might add some methods later, I also see no point using struct.
tia
@tia : yes, you could do that - in either a `class` or a `struct`. They are the same apart from default member visibility (`public` in `struct`, `private` in `class`).
Steve Townsend
@tia: I still don't get it: you seem to think that once a struct has one method, it must become a class. That looks like an excessive self-constraint to me.
ereOn
+6  A: 

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

Steve Townsend
+1  A: 

Sometimes using classes with constructors will be less performance efficient than using structs, particularly when copying large amounts of data around arrays. The reason being you can safely use functions such as memcpy to move large blocks of data around the place, whereas with a class your more likely to use an iterator and/or copy construtor.

See a previous question of mine for some further discussion on this.

Shane MacLaughlin
There's no performance difference between struct and class. In fact, other that default access there's no difference *whatsoever* between class and struct. I see what you're getting at, hence no d/v, but I think you're assuming too much semantic detail about struct vs class.
John Dibling
@John, I'm not assuming semantic detail, I'm using the semantic detail as provided in the opening question. This is pretty typical usage; when's the last time you've seen someone code up a struct with constructors?
Shane MacLaughlin
Earlier today. Yesterday, I wrote a struct without a trivial default constructor, but the compiler made one for me, so it was still not POD. You're talking about POD, which isn't the same as what the original question discussed, even if his example provided one.
Dennis Zickefoose
@Dennis, the question states 'I still use structs whenever I need pure data structures' which is pretty obviously POD (plain old data). You may write structs with member functions to avoid typing in 'public', but having looked at a lot of c++ from a lot of sources over the years, I'd guess you're in a minority.
Shane MacLaughlin
I never said anything about member functions, or access specifiers. I am simply suggesting that `struct { std::string name; };` and `struct { int id; };` are both equally "pure data structures", while only one of them is POD.
Dennis Zickefoose
@Dennis, fair enough. I misread with and without in your last response. My bad, Shane
Shane MacLaughlin
+2  A: 

It sounds like, you own a Ferrari Scaglietti and a Lamborgini Espada, sometime you drive Ferarri, sometime you drive Lamborghini.... Sometime you use struct, sometime you use class, is there any true and false?

wengseng
A: 

I used to do the following:

struct Interface
{
    virtual ~Interface() {}
    virtual void foo() = 0;
};

class Implementation : public Interface
{
    void foo(); // or public, it depends.
public:
    Implementation(...);
};

since by default, interface have all their members public, and by default, implementations have their members private.

Alexandre C.
thats exactly what I do too
pm100
I hope you did not forget the 'virtual ~Interface() {}' back then...
paul_71
This doesn't answer the question and I think it's kind of a code smell. In my opinion, structs should be used for data only (as the OP does). C++ allows structs to be like classes, but one shouldn't use structs like classes. I would also make the destructor 'protected' anyway.
ur
@ur: Protected destructors are design-dependant. And the difference between structs and classes is purely cosmetic, your "argument" is based on subjective considerations, as is mine.
Alexandre C.
+1  A: 

There is nothing wrong with using a struct in C++, I tend to avoid using classes unless I have ample time to plan out what their purpose should be.

yellowsnow