C++

STRUCTURES

A very close cousin to the class keyword is the keyword struct, which is used to declare a structure. In C++, a structure is exactly like a class, except that its members are public by default. You can declare a structure exactly as you declare a class, and you can give it exactly the same data members and functions. In fact, if you follow the good programming practice of always explicitly declaring the private and public sections of your class, there will be no difference whatsoever.

Try re-entering Listing 6.8 with these changes:

· In line 3, change class Point to struct Point.

· In line 17, change class Rectangle to struct Rectangle.

Now run the program again and compare the output. There should be no change.

Why Two Keywords Do the Same Thing

You’re probably wondering why two keywords do the same thing. This is an accident of history. When C++ was developed, it was built as an extension of the C language. C has structures, although C structures don’t have class methods. Bjarne Stroustrup, the creator of C++, built upon structs, but he changed the name to class to represent the new, expanded functionality.

DO put your class declaration in an HPP file and your member functions in a CPP file. DO use const whenever you can. DO understand classes before you move on.

Back to Index