Interview Preparation C++ Virtual, Polymorphism and Abstract class

From Embedded Systems Learning Academy
Jump to: navigation, search

Basics

To learn about virtual, let's learn about the basics of inheritance. To properly learn about virtual, and polymorphism, you need to copy and paste the code in a C/C++ compiler and run it each step of the way.

Here is the video you should watch AFTER you read through the tutorial :


/* Base class */
class printer {
    public :
        void pixel()
        {
            puts("printer pixel()");
        }
        void draw_image() {
            // Some complicated algorithm that uses our method ()
            printf("draw_image() is using : ");
            pixel();
        }
};

/* A printer model class inheriting base class */
class model_a : public printer {
    public :
        void pixel() {
            puts("model-a pixel (very sharp)");
        }
};

int main(void)
{
    /* Let's go over simple stuff */
    model_a a;
    a.pixel(); /* Prints "model-a pixel" */

    printer p;
    p.pixel(); /* Prints "printer pixel" */

    /* Let's use a pointer of type "printer" */
    printer *ptr = NULL;
    ptr = &a;
    ptr->pixel(); /* Prints "printer pixel" */
    ptr = &p;
    ptr->pixel(); /* Prints "printer pixel" */

    return 0;
}


Virtual

Now, let's modify the function of the printer :
Change : void print_pixel() { puts("printer pixel"); }
To  : virtual void print_pixel() { puts("printer pixel"); }

Now, if you run the program again, the following will occur :

void main(void)
{
    /* Let's use a pointer of type "printer" */
    printer *ptr = NULL;
    ptr = &a;
    ptr->print_pixel(); /* Prints "model-a pixel" */
    ptr = &p;
    ptr->print_pixel(); /* Prints "printer pixel" */

    /* Now, model-a's pixel method will be called because the "virtual" is
     * basically an instruction that says :
     * "Here is the function, but if a parent has the same function defined,
     *  then I will call the parent's method instead of the base class method"
     */
}

TODO - need to finish the rest


Pure Virtual

Now, let's modify the function of the printer :
Change : void print_pixel() { puts("printer pixel"); }
To  : virtual void print_pixel() = 0;

By using the = 0; at the end, we make this function pure virtual which earns the base class the names of :

  • Abstract class
  • Interface class

In plain English, this is what the base class is dictating :

  • I am an incomplete, abstract class
  • I do not know how to print a pixel
  • I require the derived class to provide the method otherwise it will be compiler error.

TODO - need to finish the rest