Lecture Notes for SE 598, Data Structures and Algorithms
31 May 2000, C++ Classes
- classes
- collections of related entities
- the collection models a single, well defined aspect of the world
- class definitions are usually split into interfaces (
.h
files)
and implementation (.cc
) files
- members
- variables, functions, types
- members may be public or private - the default is private
-
class light_switch {
public:
enum state { on, off };
void set_switch(state ss) {
switch_state = ss;
}
private:
state switch_state;
};
- scope
- anything within a class always has direct access to everything in the
class
- anything outside a class can access only the public members of a class
using the dot operator
- legal:
light_switch ls; ls.set_switch(on)
- illegal:
light_switch ls; ls.switch_state = on
- the scope operator :: is an alternative way to access class members
-
light_switch::state ls_state; ls_state = light_switch::on
- constructors
- when an object gets made, the object's constructor is called
- has the same name as the object, has no return type
- the default constructor has no parameters, or has only default-value
parameters
- the compiler creates a simple default constructor only if no
constructors are defined
- stl objects often need a default constructor
- the copy constructor has a single constructor, which is a constant
reference to an object of the same type
- the compiler will not create a default copy constructor
- stl objects often need a copy constructors
- templates
- as with functions, so with classes
- class templates parameterize classes by type
- the template types are explicitly named along with the object type
-
template <typename T> class stack { . . . }
-
stack<int> int_stk
- the C++ compiler expands each template class using the templated
definition as a pattern
- template classes cannot be split into interface and definition, and
they must be defined in each file they are used
- the STL makes heavy use of template functions
- friend functions
- a nasty problem - how to implement stream-io operators for an object
- the operators need access to the class internals
- but the operators can't be part of the class
- friend functions help out
- a friend function is a non-member function that has access to a class's
internals
- a friend function explicitly operates on class objects received through
the parameter list
- access to members via the dot operator
This page last modified on 31 May 2000.