Lecture Notes for SE 598, Data Structures and Algorithms

31 May 2000, C++ Classes


  1. classes

    1. collections of related entities

    2. the collection models a single, well defined aspect of the world

    3. class definitions are usually split into interfaces (.h files) and implementation (.cc) files

  2. members

    1. variables, functions, types

    2. members may be public or private - the default is private

      1. class light_switch {
        
          public:
        
            enum state { on, off };
            
            void set_switch(state ss) {
              switch_state = ss;
              }
        
          private:
        
            state switch_state;
          };
        

  3. scope

    1. anything within a class always has direct access to everything in the class

    2. anything outside a class can access only the public members of a class using the dot operator

      1. legal: light_switch ls; ls.set_switch(on)

      2. illegal: light_switch ls; ls.switch_state = on

    3. the scope operator :: is an alternative way to access class members

      1. light_switch::state ls_state; ls_state = light_switch::on

  4. constructors

    1. when an object gets made, the object's constructor is called

    2. has the same name as the object, has no return type

    3. the default constructor has no parameters, or has only default-value parameters

      1. the compiler creates a simple default constructor only if no constructors are defined

      2. stl objects often need a default constructor

    4. the copy constructor has a single constructor, which is a constant reference to an object of the same type

      1. the compiler will not create a default copy constructor

      2. stl objects often need a copy constructors

  5. templates

    1. as with functions, so with classes

    2. class templates parameterize classes by type

    3. the template types are explicitly named along with the object type

      1. template <typename T> class stack { . . . }

      2. stack<int> int_stk

    4. the C++ compiler expands each template class using the templated definition as a pattern

    5. template classes cannot be split into interface and definition, and they must be defined in each file they are used

    6. the STL makes heavy use of template functions

  6. friend functions

    1. a nasty problem - how to implement stream-io operators for an object

      1. the operators need access to the class internals

      2. but the operators can't be part of the class

    2. friend functions help out

    3. a friend function is a non-member function that has access to a class's internals

    4. a friend function explicitly operates on class objects received through the parameter list

    5. access to members via the dot operator


This page last modified on 31 May 2000.