/*----------------------------------------------------- Script for AdSense -----------------------------------------------------*/ /* */ /* Footer ----------------------------------------------- */ #footer { clear: both; text-align: center; color: #333333; } #footer .widget { margin:.5em; padding-top: 20px; font-size: 85%; line-height: 1.5em; text-align: left; } /** Page structure tweaks for layout editor wireframe */ body#layout #header { width: 750px; } -->

Wednesday, April 28, 2010

Classes, Structure and Union are related

Classes and Structures Are Related

Classes and Structure are very similer.The only difference is that by default the members of a class are private while, by default, the members of a struct are public. According to the formal C++ syntax, a struct defines a class type.
In fact, with one exception, they are interchangeable because the C++ struct can include data and the code that manipulates that data in the same way that a class can.

For the most part, C++ programmers use class when defining an object that contains both code and data. They use struct when defining a data-only object. (That is, struct is usually used in a way that is compatible with C-style structures.)

Unions and Classes Are Related

A union is essentially a structure in which all elements are stored in the same location. A union can contain constructor and destructor functions as well as member and friend functions. Like a structure, union members are public by default.
It is important to understand that, like a structure, a union declaration in C++ defines a class-type.
There are several restrictions that must be observed when you use C++ unions.
1) A union cannot inherit any other classes of any type.
2) A union cannot be a base class.
3) A union cannot have virtual member functions.
4) No static variables can be members of a union.
5) A union cannot have as a member any object that overloads the = operator.

Anonymous Union:
An anonymous union is a union that has neither a tag name nor any objects specified in its declaration. Also, global anonymous unions must be specified as static. Anonymous unions may not contain member functions. Finally, anonymous unions cannot include private or protected members.

Note: just because C++ gives unions greater power and flexibility does not mean that you have to use it. In cases where you simply need a C-style union, you are free to use one in that manner. However, in cases where you can encapsulate a union along with the routines that manipulate it, you add considerable structure to your program.

No comments: