I'm confused with classes, unions and structures. I already read them in books but still I'm confused. Can anybody enlighten me?
Printable View
I'm confused with classes, unions and structures. I already read them in books but still I'm confused. Can anybody enlighten me?
In C++, struct == class except that stucts are public by default, while classes are private. They are basically a collection of dataypes mixed together.
The members of a union share the same memory, so if you set one of the members you modify the others too.
Keep reading books and the web. It's difficult to explain this stuff in a few sentances.
UNION - I assume that unions are supposed to be used to make efficient use of memory. I've personally never seen unions used in a real program, only in books... I'm not saying that unions are never used... probably rarely used.
STRUCTURE - Magos is right, there is little difference between structures and classes in C++. However, typically structures do not have member functions. This is because in C, a structure cannot have member functions. (There are no classes or member functions in C.)
You can have a structure called Employee, and specific instances of that structure like Makoy and DougDbug. These structures can have variables like:
Makoy.Salary
DougDbug.Salary
Makoy.Title
Doug.Title
CLASS - In object oriented programming, a specific instance of a class is an object. Makoy & DougDbug are objects. You can have the same member variables like:
Makoy.Salary
Makoy.Title
In addition, you can have member functions like:
Makoy.IncreaseSalary()
You cannot have functions like that in non-object oriented programming languages such as C. In C, functions would have to be outside the structure. You would have to pass a pointer to the structure into your IncreaseSalary() function. You would not have encapsulation.
You can avoid structures, and always use classes if you wish.