Alibaba Group interview question

the function of C++ virtual function.

Interview Answer

Anonymous

Jul 13, 2017

virtual function means you allow to override the function if you inherit that class. for example: Class Shape has print method which print "Shape" without virtual Class Circle inherit form Shape and also implement the same print function but prints "Circle" Circle c; c.print() // output "Circle" Shape s = c; s.print() // output "Shape" So usually the expected output will be "Circle" even after the casting but this doesn't work properly because the print method wasn't defined as virtual