<<< The basic idea: redirecting calls     Index     Possible alternative: Faking it >>>

26. Virtual functions

  • 
    // Shapes.h
    class Shape {
    public:
        Shape();
        virtual void draw();
    };
    
    
    class Circle : public Shape {
    public:
        Circle( int radius );
        virtual void draw();
    };
    
    
    class Square : public Shape {
    public:
        Square( int side );
        virtual void draw();
    };
    
    
  • 
    //main.cpp
    #include "Shapes.h"
    
    void push_shape( Shape* ps, int& cnt, Shape* shapes[] );
    
    int main()
    {
        // Array of pointers to shapes:
        Shape* shapes[ 100 ] = { 0 };
    
        int shape_cnt = 0;
        push_shape( new Circle(10), shape_cnt, shapes );
        push_shape( new Square(5), shape_cnt, shapes );
    
        for ( int idx = 0; idx < shape_cnt; ++idx ) {
            // Call virtual function:
            shapes[ idx ]->draw();
        }
    }
    
    void push_shape( Shape* ps, int& cnt, Shape* shapes[] )
    {
        shapes[ cnt++ ] = ps;
    }
    
    
<<< The basic idea: redirecting calls     Index     Possible alternative: Faking it >>>