C++ 34: Function Overloading

 The process of redefining a base class function in derived classes with

exactly same prototype/signature(i.e same name same nu of arguments,same
 datatype, same return type)
as the base class function is called as function overriding.

When the baser class function does not work as per the requirements of 
the derived class object and then such a function is called needs to 
redefine the derived class.

The new function replacement of the existing base class functions of 
derived class object.

Example:
Design a class Cylinder with data memebr radius & height.
Define member functions setdata(),volume(), & surfacearea().Derived 
a class OpenCylinder (i.e Cylinder with no top surface)
from the class Cylinder having overrided function surfacearea().

#include <iostream>
using namespace std;

class Cylinder
{
protected:
    int radiusheight;

public:
    void setdata(int r, int h)
    {
        radius = r;
        height = h;
    }
    void volume()
    {
        cout << "Volume is : " << 3.14 * radius * radius * height << endl;
    }
    void surfacearea()
    {
        cout << "Surface area is: " << 2 * (3.14 * radius * radius+ (2 * radius * 3.14* height << endl;
    }
};
class openCylinder : public Cylinder
{
public:
    void surfacearea() //Function Overridng Same signature
    {
        cout << "Surface area is: " << (3.14 * radius * radius+ (2 * radius * 3.14* height << endl;
    }
};

int main()
{
    Cylinder a;
    a.setdata(25);
    a.volume();
    a.surfacearea();
    openCylinder b;
    b.setdata(25);
    b.volume();
    b.surfacearea();
    return 0;
}

Output:

Volume is : 62.8
Surface area is: 87.92
Volume is : 62.8
Surface area is: 75.36







Comments

Popular posts from this blog

C++ 38: Visibility Modes Public, Private and Protected