Introduction to Programmer Defined Types and Classes
- Review: Fundamental and Common C++ Types
- Recall the type of a variable (or object) determines two
characteristics
- What are the allowable values of the variable
- What are the allowable operations
- Up to this point we have restricted ourselves to some pretty common
program types: int, float, etc.
- The Fundamental Types: i.e., types that are part of the language
definition
- int (values: -2,147,483,648 to 2,147,483,647. operations:
+, -, *, /, ++, +=, etc.)
- float (values: -1.0+E23 to 1.0+E23. operations: +,
-, *, /, -=, <, !=, etc.)
- char (values: all ASCII symbols, e.g., 'A', '@', '?', '6'.
operations: ==, >=, +, -, etc.
- bool (values: true, false. operations: !=, &&, ||,
!, ==, ?:, etc.
- The String Type: although this is not technically a built-in type, it is
common to all standard C++ implementations.
- string: (values: any sequence of valid char elements.
operations: +, ==, !=, substr, find, etc.)
- Aggregate Types:
- arrays: these types are built from pre-existing types using the
"[]" notation
- for example: int seq[10]; declares an array of ten
integers
- Programmer Defined Types
- Most programmer defined types are aggregate types, meaning they
are a combination of more basic types.
- For example: consider the board (as in a battleship
game board)
- What constitutes a given player's game board?
- e.g., a 10x10 grid of peg holes
- what else???
- How do we represent a ship? What information do we know about
it?
- An aggregate type in C is known as a struct. Structs exist
in C++ also, because C++ was built upon the C foundation. Indeed, the
original name of C++ was "C with Classes"
- An aggregate type in C++ corresponding to the C struct is the
class
- When you define a class you are defining a new type.
- For a moment we will side step the issue of what
operations can occur on these new types and think only about the allowable
values
- In general, the allowable values are the combinations of the base data
types that "make sense"
- e.g., ships can't have a size greater than 5 or less than 2 although
you may implement the size as a short or an int.
- Programmer defined types are declared, just like others types
- Programmer defined types are passed by copy (or reference), just like
other types
- Programmer types can't generally be mixed, just like other types
- Programmer types have a limited set of allowable operations which can
act on them, just like other types
- Programmer Defined Type Examples