Sign in to follow this  
Kryodus

C++, structs vs classes/objects

Recommended Posts

Kryodus    122
Im a student in 2nd year university comp sci degree, we have mostly looked at java when it came to programming but we've done a few weeks of C++ translating java to C++ mostly. Structs were never taught to us in class, but I have been doing my own reading and they seem fairly common in many sample codes I have seen. Every example code I have seen I could program with classes/objects instead, does anyone know the advantages/disadvtanges of using classes vs structs? Structs seem a little easier to code for a lot of easy examples so far, but thats about all ive noticed. but its a very new idea to me so Im sure im missing something obvious :D

Share this post


Link to post
Share on other sites
SirLuthor    364
I'm no expert, but it seems to me that each should be used where applicable. If you have some data that is related, like the color values of a pixel, maybe 'unsigned short r, g, b;', then maybe you hsould take it, and put it into a structure. Now, if you have a few functions that work explicitly on pixel color data, then you would probably want to put those variables into a class, along with the functions that work on them. It's all a matter of what is more logical. Since structs cannot contain functions (can they? I'm fairly certain they can't, although I may well be wrong here), they should be used for sets of data, while classes should be used for grouping data and the functions that act on them, in logical formations.

Please keep in mind that again, I'm no expert, so don't take my word for this, rather, hope someone who's more experienced then me replies here [smile]

[BTW, I don't use structs at all, except when dealing with things like the Win32 API, it just doesn't seem necessary to me, when my classes illustrate the way things work better.]

[EDIT] Curses, I forgot, classes should also be used to keep data private from things that shouldn't be messing with it, because in structs, everything is public to anyone that wants to mess with it.

Share this post


Link to post
Share on other sites
stevenmarky    369
In C++ Structs are exactly the same as classes, with one minor difference -
with structs default visability is public, with classes default visability is private.

Share this post


Link to post
Share on other sites
Noir    132
Structs are generally for holding groups of variables / information to make passing like information throughout your program easier (ie. you don't want to pass 80 variables to a function when you can pass 1 structure holding them). They are a nice way of simplifying code when your problem doesn't merit a class.

I'm still kinda newb but i think that's right...

Share this post


Link to post
Share on other sites
kinglink    100
One other difference that no one has meantioned and is ESSENTIAL to understanding them is that Classes have FUNCTIONS!!! (wooo! yeaaa.. (ok I love classes and functions,))

When C was made there needed to be a way to make structures with more then just the base data types (back then there's was JUST the basic data types) So they made structs. Structs contain information on stuff that need to stay together. Very useful at the time, but as time progressed people found it less useful then originally thought as you can edit it with any thing that has access to the struct and that gets confusing, as well as the fact you still had millions of functions and all of them were called about the same way.

When C++ came around they thought they needed more work to make Structs into actual objects, and thus came the ideas of private and public variables as well as functions. This allowed the structs to no longer have everyone able to access the innermost workings of it, and allowed a VERY specific ways to work with classes as objects instead of just data lumped together.

Basically If your going to use C++ and no fear of porting you can always use classes. If you want to know when to use each, Think of it as this "do I want to have anything hidden or do I want to have any specializaed functions lumped with it?" If so use a class, if you don't mind everything being public, a struct will do the same thing as a Class, though a class does allow those wonderful functions to be added on to the end.

Now you want a brain killer, look up Unions (a C object). That's an intense concept when you first read that one.

Share this post


Link to post
Share on other sites
Mawr    278
The difference between structs and classes in c++ has already been mentioned. However, in c, they cannot contain functions. Another cool thing about structs is that if you don't have any functions/constructors/etc and no dynamic variables, you can do some quick easy storage of a struct to a file. Maybe like this:



#include <fstream>
#include <iostream>

using namespace std;

struct RGB_pixel
{
float r,g,b;
};



int main()
{
RGB_pixel pixel;
pixel.r = 1;
pixel.g = .5;
pixel.b = 0;

ofstream out;
out.open("file.dat", ios::binary);
out.write((char*)&pixel, sizeof(pixel));
out.close();

RGB_pixel pixel2;
ifstream in;
in.open("file.dat", ios::binary );
in.read((char*)&pixel2, sizeof(pixel2));
in.close();

cout << "Pixel 2 values" << endl;
cout << "R: " << pixel2.r << " G: " << pixel2.g << " B: " << pixel2.b << endl;
return 0;
}





Not 100% sure if you cannot do that with a struct/class with functions in it, testing right now.

edit: Made the code actually work. :)

edit2: It seems to me that functions don't interfere with doing raw writes and reads of the struct. Very interesting, and handy.

Share this post


Link to post
Share on other sites
SirLuthor    364
Quote:
Original post by kinglink
One other difference that no one has meantioned and is ESSENTIAL to understanding them is that Classes have FUNCTIONS!!! (wooo! yeaaa.. (ok I love classes and functions,))

No one else mentioned functions as part of classes? Did you not read my masterful post? [tears] I've found it helps to read the replies aleady posted before making assumptions [grin]

Share this post


Link to post
Share on other sites
Rebooted    612
Structs can also have functions however. As far as the language is concerned they are exactly the same apart from as someone has already said, structs have default public visibility and classes have private. Generally use structs for data only structures and classes when the structure is going to have methods.

Share this post


Link to post
Share on other sites
BlackWind    212
Quote:
Original post by Rebooted
Generally use structs for data only structures and classes when the structure is going to have methods.


why?
what would it be the advantage???

Share this post


Link to post
Share on other sites
Oberon_Command    6087
Quote:
Original post by Tsuki no Hikari
They aren't the same structs as in C.


Also, in C++, when you declare structs like this

struct Foo {
int x;
int y;
int floofy;
}


you don't have to declare variables like this:

struct Foo this_foo;

You can just do it like this:

Foo this_foo;


You would not be able to do that in C.

Share this post


Link to post
Share on other sites
Guest Anonymous Poster   
Guest Anonymous Poster
And what with memory. I heard structs are on stack, whereas classes on heap. Is that true?

Share this post


Link to post
Share on other sites
kinglink    100
SirLuthor, I appologize, though I feel the change should be shouted loudly from the roof tops or have parades dedicated to it. (I had 1 year of college with C when I already had two years of high school with C++, I sorely missed Functions in classes) as it is the true essential difference between most programmers conception of the two. But your right you did meantion it before me.

I'm sorta suprised (but not fully) that they changed structs to allow functions though I must admit they did change quite a bit. BUT these changes are still unknown to most programmers and to show a programmer a struct with a function would cause shock. I don't think I have ever personally read a source code that uses structs with functions.

The best way to do it is still to consider the struct with out functions with everything public because if your not personally declaring what should be public and private, you need to start. Just tossing a private: or public: at the begining of your definitions will blanket it all. It will definatly help readability and conform to standards as there doesn't appear to be an actual benefit from either one, that's the best way to consider it. One more thing to meantion is most people will use a Set___ and get___ function calls to tranform a open struct to a much more protected Class, so it's really up to you apparently.

So instead of
Quote:

struct Imastruct{
int x,y;
}

you can just use
Quote:

Class{
public:
inline int getx() const;//const is cool here.
inline int gety() const;
inline void setx(int r);//notice the crazy inline functions
inline void sety(int r);

private:
int x,y;
};
inline int getx()const{
return x;
}
inline int gety()const{
return y;
}
inline void setx(int r){
x=r
}
inline void sety(int r){
y=r
}


Which gives a very tight run ship, and protects from any mismatched datatypes running around accidently.

Share this post


Link to post
Share on other sites
pinacolada    834
Quote:
Original post by Anonymous Poster
And what with memory. I heard structs are on stack, whereas classes on heap. Is that true?


That's false. Structs and classes can both be either on the heap or the stack, depending on how they are declared.

Share this post


Link to post
Share on other sites
SirLuthor    364
KingLink, no problem, just thought it was kind of funny [smile] Truth to tell, I've been guilty of replying before reading replies as well, so I'm hardly the one to talk...

Regarding functions in structs, I've never seen this.. Could someone be so kind as to possibly show me an example, as another trick to add to one's books can hradly be a bad thing? Thanks!

Share this post


Link to post
Share on other sites
Guest Anonymous Poster   
Guest Anonymous Poster
Quote:
Original post by Anonymous Poster
And what with memory. I heard structs are on stack, whereas classes on heap. Is that true?


You are thinking of C#

Share this post


Link to post
Share on other sites
moeron    326
Quote:
Original post by Mawr
The difference between structs and classes in c++ has already been mentioned. However, in c, they cannot contain functions. Another cool thing about structs is that if you don't have any functions/constructors/etc and no dynamic variables, you can do some quick easy storage of a struct to a file. Maybe like this:

*** Source Snippet Removed ***

Not 100% sure if you cannot do that with a struct/class with functions in it, testing right now.

edit: Made the code actually work. :)

edit2: It seems to me that functions don't interfere with doing raw writes and reads of the struct. Very interesting, and handy.



Be careful when doing file i/o and attempting to read structures in all at one time. Its generally better to read each member seperately just in case the data structure is padded for alignment issues. In this particular case it would be ok if the compiler was doing 32bit alignment, but if it was doing 8 there would be extra dummy information in there, which could lead to problems.

Sorry if that doesn't make sense, I tried to explain it the best I could.
HtH

Share this post


Link to post
Share on other sites
lucky_monkey    440
Quote:
Original post by kinglink
Class{
public:
inline int getx() const;//const is cool here.
inline int gety() const;
inline void setx(int r);//notice the crazy inline functions
inline void sety(int r);

private:
int x,y;
};
inline int getx()const{
return x;
}
inline int gety()const{
return y;
}
inline void setx(int r){
x=r
}
inline void sety(int r){
y=r
}
That is evil. [sick] the only difference between that and your Imastruct struct is semantic. I get your point, but the example is misleading because there is no extra protection there.

Share this post


Link to post
Share on other sites
nuvem    326
I'm not sure why there's so many replies, since it's really quite simple:


// I'm a structy class!
class Foo {
public:
// Stuff goes here!
};

// I'm a classy struct!
struct Bar {
private:
// Stuff goes here!

};




There you have it folks, a struct in C++ is simply a class that defaults to public access for all members, that's it.

Share this post


Link to post
Share on other sites
Quote:
Original post by nuvem
I'm not sure why there's so many replies, since it's really quite simple:

*** Source Snippet Removed ***

There you have it folks, a struct in C++ is simply a class that defaults to public access for all members, that's it.

structs also defaults to publicly inherit from bases (wheres classes default to private).

Share this post


Link to post
Share on other sites
Fruny    1658
Quote:
One more thing to meantion is most people will use a Set___ and get___ function calls to tranform a open struct to a much more protected Class, so it's really up to you apparently.


And they'd be wrong. If you need that level of access to the class members, then it's just a glorified struct.

**Cough**. [grin]

Share this post


Link to post
Share on other sites
Ravyne    14300
Quote:
Original post by Oberon_Command
Quote:
Original post by Tsuki no Hikari
They aren't the same structs as in C.


Also, in C++, when you declare structs like this
struct Foo {
int x;
int y;
int floofy;
}



you don't have to declare variables like this:

struct Foo this_foo;

You can just do it like this:
Foo this_foo;

You would not be able to do that in C.


In C:


typedef struct FooType {
int x;
int y;
int z;
} Foo;

Foo this_foo; // Works in both C AND C++ :D





This method is also perfectly compatible with C++ so I generally use it regardless of whether or not I'm using C, just for compatibilities sake if I ever want to pull the struct into a C project.

Share this post


Link to post
Share on other sites
Ravyne    14300
Quote:
Original post by Fruny
Quote:
One more thing to meantion is most people will use a Set___ and get___ function calls to tranform a open struct to a much more protected Class, so it's really up to you apparently.


And they'd be wrong. If you need that level of access to the class members, then it's just a glorified struct.

**Cough**. [grin]


Depends. The Set() methods could be clamping values to the appropriate bounds and/or performing assertions.

I'll grant you that its still a glorified struct, but its a perfectly legitimate useage :)


[edit] I must say though, thats some impressive template work you linked to Fruny. Very interesting, did you develop that on your own or did you pick that up somewhere?

[Edited by - Ravyne on February 14, 2005 9:22:11 PM]

Share this post


Link to post
Share on other sites
Mawww    212
well i agree that in structures we usually don't have methods except for constructor and destructors

i saw many things like :

struct Blah
{
...
...
anything* pthing;
~Blah() {if (pthing) {delete[] pthing; pthing=0;}}
}

int the way i use them, the main difference between struct and class is that i dont put methods in struct (except destructors) and i don't put a "m_" prefix on structure's variables.

Share this post


Link to post
Share on other sites
petewood    819
Quote:
Original post by Mawww
well i agree that in structures we usually don't have methods except for constructor and destructors

If you have to have a destructor then that implies (to me) that the struct is responsible for looking after some important data or resources etc. It would make sense to make the data private.

In C++, structs can do everything a class can do. However people often use structs to bunch data together but which doesn't have any functionality or responsibilities. Once you start getting them (responsibilities that is), people would usually use a class. This is a style and not a neccessity.

I often use structs for things like functors, which aren't passed around or don't have any important data, or in example code on gamedev, but it is simply because it means I have to finger type less and it makes the examples shorter (not littered with public, private etc). e.g.

struct RenderThing {
RenderThing(Renderer& renderer) : m_renderer(renderer) {
}
void operator()(const Thing& thing) {
thing.Render(m_renderer);
}
Renderer& m_renderer;
};

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this