Wednesday, June 7, 2017

Overloading Across Inheritance Lines

/*This code was written by A. El-Gadi of Tripoli University for educational purposes. The code illustrates function overloading across inheritance lines in C++. For any questions use the comment section below.*/

#include<iostream>
#include<stdlib.h>

using namespace std;

class Base{public:int k;
    Base():k(rand()){};
    virtual void foo(double j){ cout<<"BASE foo(double)\n";}
    virtual void foo(int j){ cout<<"BASE foo(int)\n";}
    virtual void foo(){ cout<<"BASE foo()\n";}
    virtual ~Base(){};
};

class Der:public Base{public:
    using Base::foo;
    void foo(){cout<<"DER foo()"<<'\n';}
    };

class Chi:public Base{public:
    using Base::foo;
    void foo(double k){cout<<"CHI foo(double)"<<'\n';}
    void foo(){cout<<"CHI foo()"<<'\n';}
    };


int main(){
    Base *a[20];


for(int i=0;i<20;i++){
    switch(rand()%2){
        case 0: a[i]=new Der(); break;
        case 1: a[i]=new Chi();
        }
}

for(int i=0;i<20;i++){ a[i]->foo(1);}//behaves polymorphically, overloded
for(int i=0;i<20;i++){ a[i]->foo(1.1);}//behaves polymorphically, overloded

for(int i=0;i<20;i++){ delete a[i];}
return 0;
}

No comments:

Post a Comment