Friday, August 10, 2007

Practical Example of Using Virtual Functions

From the past few articles we have been discussing about virtual functions but we are yet to observe any of its practical use, this article would do that!

In this article we are going to show you a very simple program that illustrates the practical use of virtual functions.

Please read the code carefully!

  // Practical example of
  // when virtual functions are
  // used
  #include <iostream.h>

  class area
    int mag;
    double a;

    area(int x){mag=x;}
    double get_area(){return a;}

    // pure virtual function
    virtual void compute()=0;
    // it is made pure as
    // it couldn't have any meaningful
    // definition since area can only
    // be defined w.r.t something specific

  class circle_area : public area
    circle_area(int x) : area(x){}

    // now that we are referring
    // to area w.r.t a circle so
    // it is natural that we define
    // it
    void compute()

  class square_area : public area
    square_area(int x) : area(x){}

    // same for this!
    void compute()

  void main()
    square_area sa(10);
    circle_area ca(20);


    cout<<"Area of square: "<<sa.get_area();
    cout<<"Area of cirlce: "<<ca.get_area();

Related Articles:

No comments:

Post a Comment

You are free to comment anything, although you can comment as 'Anonymous' it is strongly recommended that you supply your name. Thank You.

Please don't use abusive language.