Sams Teach Yourself C++ in 21 Days

(singke) #1
Polymorphism 455

14


(1)Horse (2)Pegasus: 1
(1)Horse (2)Pegasus: 2
(1)Horse (2)Pegasus: 1
(1)Horse (2)Pegasus: 2
(1)Horse (2)Pegasus: 1

Just a horse
I can fly! I can fly! I can fly!
Just a horse
I can fly! I can fly! I can fly!
Just a horse

OUTPUT


FAQ
When compiling, I got a warning from Microsoft Visual C++: “warning C4541:
‘dynamic_cast’ used on polymorphic type ‘class Horse’ with /GR-; unpredictable behavior
may result.” What should I do? When running this program, I get a message:
“This application has requested the Runtime to terminate it in an unusual way. Please
contact the application’s support team for more information.”
Answer: These are some of this compiler’s most confusing error messages. To fix these, do
the following:


  1. In your project, choose Project, Settings.

  2. Go to the C++ tab.

  3. Change the drop-down to C++ Language.

  4. Click Enable Runtime Type Information (RTTI).

  5. Rebuild your entire project.
    Alternatively, if you are using the command-line compiler for Visual C++, add the /GR
    flag:
    cl /GR List1402.cpp


This solution also works; however, it is not recommended.

The desired results are achieved. Fly()is kept out of Horse, and it is not called on Horse
objects. When it is called on Pegasusobjects (line 45), however, the objects must be
explicitly cast (line 43); Horseobjects don’t have the method Fly(), so the pointer must
be told it is pointing to a Pegasusobject before being used.
The need for you to cast the Pegasusobject is a warning that something might be wrong
with your design. This program effectively undermines the virtual function polymor-
phism because it depends on casting the object to its real runtime type.

ANALYSIS

Free download pdf