C Plus Plus structure
From ArticleWorld
A C++ structure is a basic C++ data type that resembles C++'s class type and C's traditional structures. Just like C++'s classes, a C++ structure can have member functions, constructors, destructors and operator overloads, but its default accessibility is public instead of private. It also resembles C structures, as they are also declared using the struct keyword. However, the declaration itself is not compatible with its C equivalent.
Contents |
Usage
Using structures in C++ is quite straightforward. In fact, anyone who has had to do with C will find it easy enough:
#include <iostream> #include <string> struct pupil { string name; float time; }; int main () { pupil x, y; x.name = "Jones"; y.name = "Taylor"; x.time = 91; y.time = 75; cout << x.name << "finished in " << x.time << "seconds" << endl; cout << y.name << "finished in " << y.time << "seconds" << endl; }
It should be fairly easy to realize what this program outputs.
Member functions
You can easily add member functions to a structure:
struct pupil { string name; float time; void printName() { cout << name; } };
Structures may have contructors and destructors as well:
struct pupil { string name; float time; void printName() { cout << name; } pupil(string theName, time theTime) { name = theName; time = theTime; } ~pupil() { cout << "I'm killing myself"; } };
The usage of destructors is, however, less widespread than that of the constructors. Few structures actually need an overloaded destructor.
Other features
C structures also have support for operator overloading and can be used as a template. They can be used with the reference operator (&) when passed to a function, so that the amount of memory consumed on the stack is minimized.
Controversy
The C++ structures were subject to a great deal of controversy. The extra added keywords break the compatibility with C, and many argued that the usage of overloaded operators (<<, >>, +=) can lead to confusions. While convenient for many, the C++ structures are still subject to many endless debates.