Polymorphism - Cmartinez-28/2143-OOP GitHub Wiki

Definition

Polymorphism in OOP allows a function or method to have the same name or logic with only slight differences, but behave differently based on input. There are two different types of polymorphism, static and dynamic. Static polymorphism is resolved at compile-time and is used with method overloading and operator overloading. Dynamic polymorphism is resolved at run-time and used for function overriding and virtual functions.

Purpose

Polymorphism allows objects of different types to be treated as instances of a common superclass. It makes code reusable and more manageable, reducing complexity. Function overloading allows the user to create instances of a class with different types and amounts of data members. Operator overloading redefines the behavior of operators such as +,-,<<, for user-defined types.

Code Example

Class Student
{
   int age, hours;  //private data members
   string major, name;
   float gpa;
public:
   //Methods with same name as class, different parameters
   Student();
   Student(int,int,string,string,float);
   Student(int,string,string);
}

Common Mistakes

  • Overusing Inheritance
  • Forgetting to use virtual key word
  • Improper usage of base class pointers