CIS 250 - 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:
struct obj { int i; }; obj* pobj = new obj; (*pobj).i = 32; pobj->i = 16;
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