Polymorphism and C++

Table of Contents

  1. Review
  2. C++ Polymorphism
  3. Virtual


Review

Happens mostly when we have a hierarchical inheritance

The change/difference at the same level of inheritance

A base class like animal with many others

Mechanisms

“IS A” relationship

Overriding

Redefinition vs changing of parameters, Override and Overload respectively

C++ Polymorphism

IS A relationship is already established, no extra code required
Overriding requires the use of a keyword

Virtual Keyword

Instead of Java opt-out with const keyword (final) we have to opt-in with C++

Virtual

Without the virtual keyword, the execution will default to the parent method’s definition

The virtual keyword tells the compile to examining the nature of the object and call appropriate method instead

Virtual vs Pure Virtual

Create a method within the parent class to be a default behavior

This can also be taken to create an Abstract base or Pure Virtual Method

Pure Virtual methods have no definition in the parent

Consequences of Pure Virtual

First:

Second:

Pure Virtual - Interface

C++ doesn’t have interfaces in the same way as Java

Interface in Java:

In C++ interfaces are created through the use of Pure Virtual Methods and multiple inheritance The Abstract Base Class could consist of Pure Virtual methods and those methods MUST be defined by the child

Interface Class:

Pure Virtual Within a Body

Pure Virtual methods can be marked with =0 and provide a body Different than interfaces in Java Java interfaces cannot have a body in their methods

virtual const char* speak() = 0
//The  = 0 means this function is pure virtual
{

	return "hello"; //even though it has a body

}

The child class is still forced to implement the pure virtual … but it doesn’t necessarily have to provide its own definition It can use :: and call on the parent classes definition

Object Slicing

The “IS A” relationship isn’t perfect When using a Base Class reference, the compiler ONLY knows about the base class methods
When assigning a derived class to a base class reference, the expanded portion of the derived class is “sliced off”

This can be avoided with pointers