Pointers, virtual functions, abstract classes

Objectives

  • Use pointers
  • Use virtual functions
  • Use pure virtual functions
  • Explain what makes a class abstract

Pointers

  • Declaring a pointer: int *p;
  • Initializing a pointer: p = &n; // assumes n is an int variable
  • Using a pointer: *p = 55;
  • Using a pointer to a struct:

Dynamic memory allocation

  • Allocating memory dynamically: int *p = new int;
  • Deallocating memory: delete p;
  • Allocating an array dynamically: int *p2 = new int[10];
  • Deallocating an array: delete[] p2;
  • Allocating an object's memory dynamically: obj *p3 = new obj;
  • Deallocating an object's memory: delete p3;
  • If a class dynamically allocates memory, you should write a destructor for it to deallocate the memory (to replace the default one written for it)
  • If a class dynamically allocates memory, you should probably write an assignment operator overload for it (to replace the default one written for it)
  • If a class dynamically allocates memory, you should write a copy constructor for it (to replace the default one written for it)
  • If a class dynamically allocates memory, you should write a default constructor if one is wanted (to replace the default constructor provided)
  • A base class with a destructor to deallocate memory should make the destructor virtual

Virtual functions

  • Compile-time binding is also called static binding and early binding
  • Early binding sets what functions will be called at compilation
  • Run-time binding is also called dynamic binding and late binding
  • Late binding decides which functions to call (base or derived class) at run time
  • The keyword virtual makes a function late binding
  • The keyword virtual is only used in the base class
  • A pure virtual function has no body; it is specified with this in place of the body: =0;
  • It is up to derived classes to implement the pure virtual functions of the base class
  • Classes with one or more virtual functions are called abstract classes
  • Abstract classes can not be instantiated