Chapter 2: Introducing Classes

 This chapter introduced the fundamentals of defining and using classes. The emphasis was on creating simple, useful classes in this chapter, so that in future chapters we can deal with the more subtle aspects of class design.

An object has three properties: its state, consisting of the current values of its data members; its behavior, implemented as member functions; and, its identity, which makes it distinct from all other instances of the same class.

Object-oriented programs attempt to model real-world problems and applications. Because of this, objects in a program usually have a close correlation to the real-world objects in a certain problem domain.

A link relationship exists when a class member function sends messages to an object of another class. A composition relationship exists when a class contains data members that are class objects themselves.

Objects in programs hide their details, presenting only an outside view, called an interface. An interface is an abstracted or simplified view of an object that is presented to the object's user.

Classes can be given the same rich set of behaviors that characterize C/C++ built-in data types.

A class name whose definition is not nested inside a function or another class has file scope and external linkage. For such a class, the class name defines a type, and objects of that type can be declared anywhere in the same program.

By default, class members are private, meaning that they have class scope and can only be accessed by functions in the same class or by friends of the class. On the other hand, class members that are declared public are accessible from outside the class. Each class member name must be unique within the class scope.

Member functions are categorized as constructors, destructors, operators, selectors, modifiers, and iterators. A constructor is a member function that runs automatically whenever a class variable is defined. The compiler automatically generates a default constructor if and only if you have not defined any constructor for the class. A destructor is a member function that executes when a class variable is logically deleted. A destructor has no parameters or return type. A class can have only one destructor.

Rarely should a class contain public data members, as this makes it impossible for the class to regulate changes to its own data. Member functions that will only be called from other member functions and friend functions in the same class should be made private.

While a program is in its develpment and testing phases, some programmers believe that inline functions should be avoided. Runtime efficiency is rarely important until after a program has been thoroughly debugged and tested, at which point, critical areas of code can be optimized to improve runtime efficiency.