Procedural-based Programming by ajizai


									     C++ Classes

          Fred Kuhns
Computer Science and Engineering
Washington University in St. Louis

                             Some definitions
• Translation unit (TU): what is processed by the compiler
• The “one-definition rule” or ODR: Each class (or enumeration,
  template, function etc) must be defined exactly once in a program
   – it is possible to have two definitions if they are in different TUs and are
     identical … but it is best to avoid this situation!
• Across translation units:
   – Use name of functions, classes, templates, variables, namespaces and
     enumerations consistently
   – declare each class, …, consistently. Note the extern keyword asserts that
     what follows is a declaration and not a definition.
• Linkage:
   – eternal linkage: a name that can be used in TUs other than the one in
     which its is defined
   – internal linkage: only available in the immediate TU.
• An inline function must be identically defined in every TU in which
  it is used. Place in a header or other (.i) include file.
• const and typedefs by default have internal linkage. If you want
  them to be global then place in a header file.
   Fred Kuhns (12/19/2011)    CS422 – Operating Systems Concepts              2
What to put in header files (see [Stroustrup])
                  Yes                                            No
 •   Named namespaces                            •   Ordinary function definitions
 •   Type definitions                            •   Data definitions
 •   Template declarations                       •   Aggregate definitions
 •   Template definitions                        •   Unnamed namespaces
 •   Function declarations                       •   Exported template definitions
 •   Inline function definitions
 •   Data declarations
 •   Constant definitions
 •   Enumerations
 •   Name declarations
 •   Include directives
 •   Macro definitions
 •   Conditional compilations
 •   Comments

  Fred Kuhns (12/19/2011)   CS422 – Operating Systems Concepts                 3
                              Class Introduction
•   Type: concrete instance of a concept, said to model the concept.
•   Concept: places a set of requirements on a type
•   Class: user defined type, separate implementation from properties
•   Concrete type: simple, not derived
•   typical concrete Class structure:
    class Date {
        int d, m, y;
    public: // default is private
        -- constructors --
        -- access methods (const)--
        -- manipulator methods --
        -- implicit or explicit copy operators --
        -- exception class –
• Member functions may be defined in separate context (for example
  the .cc file with the class declaration in a .h file).
• If a member function is defined in the declaration then it is inlined.
    Fred Kuhns (12/19/2011)     CS422 – Operating Systems Concepts      4
                          Access control
• Access control: use public or private keywords
  (default is private). A struct is == class with all
  members public. Non-member functions can not access
  private members.

          class Date {
               Date(int m, int d, int y);
               int m_, d_, y_;

Fred Kuhns (12/19/2011)   CS422 – Operating Systems Concepts   5
                            static class members
• A static member is part of the class but not of any particular object
  (instance of the class).
• Static object referenced using class name, Date::default_date
• Must define static members someplace, usually outside of class.
   – non-const data members must be initialized outside of class
class Date {                                  Date Date::default_date(01,01,2004);
   int d_, m_, y_;
   static Date default_date;                  void Date::set_default(int m, int d, int y)
public:                                       {
   Date(…);                                      Date::default_date = Date(m, d, y);
   …                                          }
   static void
Date::Date(int m, int d, int y)
   d_ = d ? d_ : default_date.d_;
   m_ = m ? m_ : default_date.m_;
   y_ = y ? y_ : default_data.y_;
  Fred Kuhns (12/19/2011)      CS422 – Operating Systems Concepts                    6
              Constant member functions
• You will generally have a set of methods whose only
  purpose is to access object data.
    class Date {
      int day() const;
    int day() const { return _d; };
• The const indicates the method will not modify the
  object’s state.
    – The const keyword is part of the member functions type and
      must be repeated when defined
• A non-const method can not be invoked on a const
  object but a const member function can.

Fred Kuhns (12/19/2011)   CS422 – Operating Systems Concepts       7
                            Self Reference
• All object member functions (non-static) are invoked
  with a pointer to itself
   – non-const member function: X * const this;
   – const member function; const X *const this;
• the “this” pointer is implied when member fields are
  accessed within a member function
• You can use this to return a reference to the ojject
   Date& Date::add_year(int n)
     if (…) {…}     // check for leap year
     _y += n;       // this-> implied
     return *this;

  Fred Kuhns (12/19/2011)    CS422 – Operating Systems Concepts   8
                          Helper functions

• generally you should only place into class definitions
  those methods which need direct access to object

• helper functions are those functions which can be
  defined outside of the class.
    – Usually either in the same file or in a utility library.

• This may include some of the overloaded operators.

Fred Kuhns (12/19/2011)    CS422 – Operating Systems Concepts    9
                          Creating objects
• named automatic object
• free-store object (new/delete)
• nonstatic member object
• array element
• local static object
• global, namespace, or class static object
• temporary object
• indirect instantiation: allocate memory then define it
  to contain an object
• union member

Fred Kuhns (12/19/2011)    CS422 – Operating Systems Concepts   10
• A class constructor has the same name as the class
    Date {
      Date(int, int, int); // class constructor
      Date(); // default constructor
      Date(int m, int d=0, int y=4); // default args

    Date::Date(int m, int d, int y)
      m_ = m; // always required
      d_ = d ? d : today.d_; // 0 is invalid, today is global
      y_ = y; // by default a valid year is given
• establishes invariant for the class (what must always be true)

  Fred Kuhns (12/19/2011)   CS422 – Operating Systems Concepts     11
                          Initializing Objects
• Classes may have other classes as members
• specify class constructor parameters in the members initializer
    class Grades {…Grades(string);...};
    class Student {
      char *name;
      Grades g;
      Student(char *n=NULL) : name(0), Grades(“A”)
      { … }
• constructors for members in initializer list are
    – called before entering the constructors body
    – called in order they are listed in class declaration
• The destructor for the member objects are called after the
  object’s destructor
• Must use initialize list for reference members, consts and any
  member objects without default constructors.

Fred Kuhns (12/19/2011)      CS422 – Operating Systems Concepts     12
• Static integral constants may be initialized within class
  declaration by a constant expression.
  static const int MAX = 100;
• you must also define outside of class
  const int MAX; // but don’t reinitialize
• or you can use enumator
  enum {MAX = 100, MIN = 0, …};
• You can define an array of a class T iff T has a default
  constructor. Further, the destructors for all elements in
  the array are called when the array is deleted.
  delete X; // delete element X
  delete [] X; // delete array X

  Fred Kuhns (12/19/2011)   CS422 – Operating Systems Concepts   13
                          Temporary Objects
• Temporary objects may be created during the evaluation of an
• it is destroyed at the end of the expression
    // s1, s2 and s3 are of type string
    const char* cs = (s1+s2).c_str();
    cout << cs;
    if (strlen(cs=(s2+s3).c_str())< 8 && cs[0] == ‘a’) {
        … do something …
• temporary can be used to initialize a const reference or named
  named object
    const string& s = s1 + s2; // const reference
    string str = s1 + s2; // named object
    string& sx = s1 + s2; // error
• Another way to create a temporary object:

Fred Kuhns (12/19/2011)      CS422 – Operating Systems Concepts    14
• In rare cases you may need to expose internal (protected
  or private) member items to other classes.
• Generally this indicates there is an error in your design
  but occasionally there is no other way
• C++ defines the friend mechanism to selectively allow
  other classes, class methods or functions to access
  nonpublic members
• A friend declaration can only appear within a class
class SomeClass {
    friend class AnotherClass;
    friend int ClassX::find(ClassX::size_type len);
    friend ostream& operator<<(ostream& SomeClass&);

  Fred Kuhns (12/19/2011)   CS422 – Operating Systems Concepts   15
• Member functions                         • Static member functions:
  declaration permits                            – access to private items
                                                 – defined within scope of class
   – access to nonpublic
     members                               • friend functions, declared in class
   – must be invoked on an                       – access to private items
     object                                • may befriend a function or an
                                             entire class.
            class Complex {
              friend Complex operator+(const Complex& a, const Number& b);
            class Number {
              friend Complex operator+(const Complex& a, const Number& b);
            Complex operator+(const Complex& a, const Number& b)
              Complex tmp(,;
              return tmp;
 Fred Kuhns (12/19/2011)    CS422 – Operating Systems Concepts                     16
                          Default constructor
• Takes no arguments

• Compiler will generate a default constructor unless
    – (1) the class defines any constructors
    – (2) class contains a const or reference type
    – (3) class contains an object without a default constructor

• Built-in types are initialized using the same rules as
  already described: local scope not initialized, global
  scope initialized to zero.
    – Preserves compatibility with C

Fred Kuhns (12/19/2011)      CS422 – Operating Systems Concepts    17
• While constructors create new instances of a class, a destructor
  is used to “clean up” after an object is no longer needed.
    – ~X : destructor for object X
• Implicitly called when object is destroyed
    – is not called when pointers and reference to objects go out of scope.
    – However if delete is called on a pointer then the corresponding
      destructor is called.
• Member objects have their destructors called in the reverse
  order of their declarations.
• If a destructor is not defined the compiler will synthesize one.
• Common scenario: constructor allocates some resources (memory)
  then a destructor is defined to release this memory when object
  is deleted.

Fred Kuhns (12/19/2011)   CS422 – Operating Systems Concepts              18
    More on constructors/destructors
• Destructor example
• Constructor allocates memory for string
• Destructor must deallocate memory
                                 Student::Student (char *n)
                                   if (n == NULL) {
 class Student {                     name = new char[DefBufSz];
   char *name_;                      *name = ‘\0’;
   …                               } else {
 public:                             name = new char[strlen(n)+1];
   Student(char *n=null);            strcpy(name, n);
   ~Student();                     }
   …                             }
 }                               Student::~Student()
                                   cout << “Calling destructor\n”;
                                   if (name)
                                     delete [] name;

Fred Kuhns (12/19/2011)   CS422 – Operating Systems Concepts         19
• The operator new allocates memory from the free
• the operator delete frees memory allocated by new
• you must free all memory allocated (no garbage
• it is an error to call delete two or more times on the
  same memory location
• you can overload (redefine) these operators, the
  placement syntax
    void *operator new(size_t, void *p) {return p;}
    void *buf = reinterpret_cast<void *>(0xf00f);
    X* p2 = new(buf)X;

Fred Kuhns (12/19/2011)   CS422 – Operating Systems Concepts   20
                          Multiple inheritance
• Overload resolution is not applied across class scope
  boundaries. So if two different base classes define a
  function with the same name, then you have an
    – Be explicit, Base1::fn() or Base2::fn()
    – use a using-clause, using Base1::fn(); using Base2::fn()
• What about replicated base classes?
    – ambiguities related to which base is being referenced
    – you should write an overriding function in the derived class
• Virtual Base Classes
    – ensures only one copy of base object is constructed.
    – initialization of virtual base class is responsibility of the most
      derived object.

Fred Kuhns (12/19/2011)      CS422 – Operating Systems Concepts        21
             Run-Time Type Information
• dynamic_cast : if p is a pointer to class T* then the
  address is returned, otherwise 0. Alternatively, if p a
  reference to type T (i.e. T&) then the assignment is
  made, otherwise can exception is thrown.
• Restricting: type T must be a polymorphic type
• static_cast<T*>(p) does not examime the underlying
• There is also a typeid() operator that returns type
  information (including a name string)
    – if polymorphic type then actual derived type is returned
    – otherwise the expression type is returned.

Fred Kuhns (12/19/2011)   CS422 – Operating Systems Concepts     22

To top