-
Struct vs Class
Hey All,
I need to know where I can find some documentation on the fundamental differences between C++ structures and classes. I know that with structures everything is public, and with classes everything is private by default. So data and functions can be hidden. But I'm not finding much more than that, as far as differences. So can somebody point me in the right direction. I would really appreciate it.
:D
-
In C++, there is no difference other than the one you stated: structs are public access by default, whereas classes are private. I think the general rule is to use a class when you have member functions and / or need to hide data; uses structs for simple things that are all public:
Code:
struct Force
{
int x;
int y;
double angle;
int magnitude;
};
Code:
class MovingObject
{
public:
MovingObject(int initialx, int initialy);
void Move();
void ApplyForce(const Force& force);
private:
int x, y, dx, dy;
};
-
functions
Correct me if i'm wrong, but classes enable you to assign functions to your objects. It would be annoying to have to write a fuction that always took an object reference as a parameter, it's much easy to do stuff like objectclass.draw();
Oh, and classes allow teplating, and time-saving stuff like STL, which is REALLY useful...
Ooohhh...and with classes you can do stuff like inheritence and have protected variables, etc.
Sorry. I used to be a VB programmer, then i moved to C++ and found CLASSES!!!!
-
You can do all of that with structs in C++ :)
-
The one other difference I forgot is the default inheritance modifier;
Code:
on structs, saying
struct foo : bar
{
};
is equal to
struct foo : public bar
{
};
whereas for classses:
class foo : bar
{
};
is the same as
class foo : private bar
{
};
-
Wow, thanks to all who replied...:D ...this is great, I'm coming from a Cobol background, so this is all new to me. Inheritance, is this along the lines of the polymorphism concept. Sunburnt, what is bar in your example, another struct or class?
Thanks again.
And Parksie is correct about structs in C++, you can assign member functions.
-
yup; that second part isn't very important; if you always specify what type of inheritance you want (public / private) you'll never run into problems, and your code will probably be clearer.