Answer to Question #217209 in C++ for Chirag

Question #217209

1. Function Overloading : Compile time polymorphism: early binding: same function name with different types and number of arguments.

2. Virtual function: Run-time polymorphism: late binding: call function depending on where base pointer is pointing to.


1
Expert's answer
2021-07-14T18:31:07-0400
  1. Compile-time polymorphism: This type of polymorphism is achieved by function overloading or operator overloading.
  • Function Overloading: When there are multiple functions with same name but different parameters then these functions are said to be overloaded. Functions can be overloaded by change in number of arguments or/and change in type of arguments.


Example:

// CPP program to illustrate 
// Operator Overloading 
#include <iostream>
using namespace std;

class Complex { 
private: 
  int real, imag; 
public: 
  Complex(int r = 0, int i =0) {
    real = r;
    imag = i;
  } 
  // This is automatically called when '+' is used with 
  // between two Complex objects 
  Complex operator + (Complex const &obj) {
    Complex res;
    res.real = real + obj.real; 
    res.imag = imag + obj.imag; 
    return res; 
  } 
  
  void print() { cout << real << " + i" << imag << endl; }
};

int main() { 
  Complex c1(10, 5), c2(2, 4); 
  Complex c3 = c1 + c2; // An example call to "operator+" 
  c3.print(); 
}
  1. Runtime polymorphism: This type of polymorphism is achieved by Function Overriding.
  • Function overriding on the other hand occurs when a derived class has a definition for one of the member functions of the base class. That base function is said to be overrided.


// C++ program for function overriding 

#include <bits/stdc++.h>

using namespace std; 

class base
{
public:
  virtual void print ()
  { cout<< "print base class" <<endl; }

  void show ()
  { cout<< "show base class" <<endl; }
}; 

class derived:public base
{
public:
  void print () //print () is already virtual function in derived class,
                //we could also declared as virtual void print () explicitly
  { cout<< "print derived class" <<endl; }

  void show ()
  { cout<< "show derived class" <<endl; }
}; 

//main function 
int main() { 
  base *bptr; 
  derived d; 
  bptr = &d; 

  //virtual function, binded at runtime (Runtime polymorphism) 
  bptr->print(); 

  // Non-virtual function, binded at compile time 
  bptr->show(); 

  return 0; 
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS