Interview Preparation C++ Virtual, Polymorphism and Abstract class
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.
/* Base class */
class printer {
public :
void print_pixel() {
puts("printer pixel");
}
};
/* A printer model class inheriting base class */
class model_a : public printer {
public :
void print_pixel() {
puts("model-a pixel");
}
};
void main(void)
{
/* Let's go over simple stuff */
model_a a;
a.print_pixel(); /* Prints "printer pixel" */
printer p;
p.print_pixel(); /* Prints "model-a pixel" */
/* Let's use a pointer of type "printer" */
printer *ptr = NULL;
ptr = &a;
ptr->print_pixel(); /* Prints "printer pixel" */
ptr = &p;
ptr->print_pixel(); /* Prints "printer pixel" */
/* In both cases above, we will see "printer pixel" being printed
* because the type of the pointer is "printer", so it will always
* call the printer's print_pixel() method
*/
}
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
:
By using the
Change : void print_pixel() { puts("printer pixel"); }
To : virtual void print_pixel() = 0;
= 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 parent class to provide the method otherwise it will be compiler error.
TODO - need to finish the rest