Game Development Community

Structs with funcs

by Joe Spataro · in Technical Issues · 02/09/2005 (12:14 am) · 4 replies

Hello,
I am trying to learn C++ and the amount of "stuff I've never seen before" seems to never end.

So I was nosing around in shapebase.h and I ran into something that none of my c++ books cover. I noticed that the struct ShapeBaseImageData has a constructor and a destructor, as well as the functions onAdd(), preload(), lookupState() etc... In addition, in the class ShapeBase, there is the line

friend class ShapeBaseImageData;

but the decl of ShapeBaseImageData is a struct

struct ShapeBaseData : public GameBaseData {
private:
typedef GameBaseData Parent;

So I got confused, because all my books dont mention that structs have constructors, or contain funcs, or that 'friend class MyStruct' could be used... Can someone explain what I can and cannot do with structs?

joe.s

#1
02/09/2005 (12:25 am)
Generally c++ structs don't have methods, but they can. Basically, a c++ struct is the same as a class, but with default public access instead of private. Not sure what's up with it being friend class instead of friend struct, though.
#2
02/09/2005 (5:40 am)
It didn't appear in your book because it is not generally encouraged. Struct is for when you just want to lump a few variables together and call it one object. Class is for when you want to do something fancy, use encapsulation, etc. This is a matter of readability. When you call something a struct or class, there are certain expectations. That aside, the only technical difference, as Adam said, is whether members are public or private by default. In my programming, everything in a struct is public and I don't use the public or private tags. In a class there is a mix of both, and I always use the tags so the default doesn't matter.
#3
02/09/2005 (7:34 am)
The other difference is that structs use public inheritance by default.

People don't like to put methods in structs because it gives headaches to poor old programmers who worked in C before they learned C++.
#4
02/09/2005 (12:58 pm)
>poor old programmers who worked in C before they learned C++

I'm one of those. I heard from quite a lot of people that learning C was a good warm up for learning C++ and that I wouldn't have to unlearn anything. In hindsight, I totally disagree. While they share the same background, and while it is possible to do C style programming in C++... C++ done right is totally different from C. I had to unlearn at least half of the knowledge and habits that I picked up in C. The only good thing I found about C is that it's easier to find good books on it.