Basic Concepts

Before giving examples of C++ features, I will first go over some of the basic concepts of object-oriented languages. If this discussion at first seems a bit obscure, it will become clearer when we get to some examples.

  1. Classes and objects. A class is similar to a C structure, except that the definition of the data structure, and all of the functions that operate on the data structure are grouped together in one place. An object is an instance of a class (an instance of the data structure); objects share the same functions with other objects of the same class, but each object (each instance) has its own copy of the data structure. A class thus defines two aspects of the objects: the data they contain, and the behavior they have.

  2. Member functions. These are functions which are considered part of the object and are declared in the class definition. They are often referred to as methods of the class. In addition to member functions, a class's behavior is also defined by:
    1. What to do when you create a new object (the constructor for that object) -- in other words, initialize the object's data.
    2. What to do when you delete an object (the destructor for that object).

  3. Private vs. public members. A public member of a class is one that can be read or written by anybody, in the case of a data member, or called by anybody, in the case of a member function. A private member can only be read, written, or called by a member function of that class.

Classes are used for two main reasons: (1) it makes it much easier to organize your programs if you can group together data with the functions that manipulate that data, and (2) the use of private members makes it possible to do information hiding, so that you can be more confident about the way information flows in your programs.