[Cs3] Object Pointers and Virtual Functions
Mikhail Nesterenko
mikhail at cs.kent.edu
Fri Mar 18 14:22:53 EDT 2022
>
>
> 1. My first question in regards to the virtual.cpp program. In main, there is
> the line `Figure *fp = new EmptySquare(5)`. My question was what would
> happen if instead it was `Square *sqr = new EmptySquare(5)`, and I believe
> you brought the possibility of situations like ?EmptySquare *emptySqr = new
> Square(5)`.
This is called "invoking a method on a sister (or sibling) class" and
is allowed. This is easily accomplished through vtable mechanism as we
discussed in class (Slide 9 in the Template Method lecture).
Here is more details on sister class method invocation from
stackoverflow.
https://stackoverflow.com/questions/17280329/delegation-to-sister-class
> 2. My second question is in regards to the use of the virtual functions in
> general, as wouldn?t `EmptySquare emptySqr2(5)` and `emptySqr2.draw()` do
> the same as ?Figure *fp = new EmptySquare(5)` and `fp->draw()`; at least if
> the overwritten function was defined in the derived class? Is it just bad
> practice to do the former even if it offers the same result but with quick
> binding?
Polymorphism (invoking a member function based on the object it is
invoked on) is implemented using pointer or references in C++.
In case of operating on objects directly, like in your example:
EmptySquare emptySqr2(5);
emptySqr2.draw();
There is now ambiguity as to which draw() to invoke: the one of the
class that emptySqr2 belongs to. Now, a pointer (of the base or
derived class) may point to any of the objects in the inheritance
hierarchy. Therefore, through virtual functions (and vtables), the
specific function to be invoked is resolved.
Thanks,
--
Mikhail
More information about the cs3
mailing list