One C++ polymorphism quesion
Posted on 2015-05-24 19:58:27 +0900 in C/C++
Confusing subtype polymorphism
When I first began to learn the polymorphism of C++, the Subtype Polymorphism
similar to the following confused me a lot.
Now the programme can uses different subtypes
to call do_meowing
.
The output is:
Meowing like a regular cat! meow!
This is the Felid
Meowing like a tiger! MREOWWW!
This is the Felid
Meowing like an ocelot! mews!
This is the Felid
So, only the virtual function
is polymorphism, but why and how?
polymorphisms in C++
There are four polymorphisms in C++, namely
- Subtype Polymorphism (Runtime Polymorphism)
- Parametric Polymorphism (Compile-Time Polymorphism)
- Ad-hoc Polymorphism (Overloading)
- Coercion Polymorphism (Casting)
virtual function
belongs to the subtype polymorphism
category.
subtype polymorphism implementation
Each object owns several fields, including
- data member
- inherited data member
- virtual table
subtype polymorphism
in C++
is implemented by virtual table
variable.
Also note that, member function is not stored in the object level, but in the class info level. So normal member function is only determined by its declared type, not polymorphismed.
Hide Comments
comments powered by Disqus