Struct and Class

Jun 28, 2014 at 10:56pm
Hi!

Can someone point out in which case i should use a struct in side a class?
Because, as far as I understand, they (struct and class) are more or less the same thing.

Thanks.
Jun 28, 2014 at 11:23pm
The only difference between struct and class is that members of struct are public by default. Members of class are either private or protected, I can't remember which.
Jun 28, 2014 at 11:47pm
Structs are used to group data together(good for passive data), that data is public by default, and a struct cannot use functions. Classes are more powerful, they also group data, their data members are private by default, and they can use member functions. The data in a class has a strong relationship with its member functions, this is important and structs don't have that. Some of these functions include, constructors and destructors. classes also allows for inheritance and polymorphism, and more importantly encapsulation.

Sometimes, when we use structs we are throwing away an important part of object oriented programming, encapsulation. Encapsulation is the process of hiding information. When we limit the action of freedom, we have a clearer picture on how to use that information so it can be used as intended. If we forget this important concept we are susceptible to data corruption. I would recommend that you use classes.
Last edited on Jun 29, 2014 at 1:03am
Jun 29, 2014 at 12:38am
In C++ they are identical except:
structs are public by default
classes are private by default

What Gkneeus said about structs not being able to use functions was true in C, not C++.
Jun 29, 2014 at 1:05am
Ya your right, thanks for clearing that up. I have been learning C lately and am getting them a little mixed up.
Topic archived. No new replies allowed.