I have visited quite a few links by now.
I seem to understand how to use the keyword virtual
.
But I still haven't got an insight as what it does to a function. ( leave alone classes!)
I have a few guesses as what it might do..
Please allow me to explain myself through the following code fragments
Classes
class stars
{
public :
void describe { cout << "Stars are bright objects\n"}
};
class sun : public stars
{
public:
void describe { cout << "Sun is visibly the most brightest star\n";}
};
Main Function
void main()
{
sun *ptr = new sun;
stars *spt = ptr;
ptr -> describe(); //Output line1: "Sun is visibly the most brightest star"
spt->describe(); //Output line2: "Stars are bright objects"
((sun*)stp) -> describe() //Output line3: "Sun is visibly the most brightest star"
}
Now, had I used virtual
before void describe()
in class stars
.
The second line would have been different.
I believe it's because, the keyword virtual influences the way the function works.
(i.e) while executing stp -> describe();
the function stars::describe()
finds the object type associated with the address stored in stp, and accordingly prioritizes the function to be called.
Please comment, if I didn't make myself clear (this is my first question)
Thank you for sparing your precious time for reading this, I really acknowledge it