Sams Teach Yourself C++ in 21 Days

(singke) #1
Understanding Object-Oriented Programming 139

6


Creating New Types ............................................................................................


Programs are usually written to solve real-world problems, such as keeping track of
employee records or simulating the workings of a heating system. Although it is possible
to solve complex problems by using programs written with only numbers and characters,
it is far easier to grapple with large, complex problems if you can create representations
of the objects that you are talking about. In other words, simulating the workings of a
heating system is easier if you can create variables that represent rooms, heat sensors,
thermostats, and boilers. The closer these variables correspond to reality, the easier it is
to write the program.
You’ve already learned about a number of variable types, including unsignedintegers
and characters. The type of a variable tells you quite a bit about it. For example, if you
declare Heightand Widthto be unsigned shortintegers, you know that each one can
hold a number between 0 and 65,535, assuming an unsigned shortinteger is two bytes.
That is the meaning of saying they are unsignedintegers; trying to hold anything else in
these variables causes an error. You can’t store your name in an unsigned shortinteger,
and you shouldn’t try.
Just by declaring these variables to be unsigned shortintegers, you know that it is pos-
sible to add Heightto Widthand to assign the result to another number.
The type of these variables tells you


  • Their size in memory

  • What information they can hold

  • What actions can be performed on them
    In traditional languages such as C, types were built in to the language. In C++, the pro-
    grammer can extend the language by creating any type needed, and each of these new
    types can have all the functionality and power of the built-in types.


Downsides of Creating Types with struct
Some capabilities to extend the C language with new types were provided by the ability
to combine related variables into structs, which could be made available as a new data
type through the typedefstatement.
There were things lacking in this capability, however:


  • Structsand the functions that operate on them aren’t cohesive wholes; functions
    can only be found by reading the header files for the libraries available and looking
    for those with the new type as a parameter.

Free download pdf