Polymorphism
Hello. Why should we cast the vector type as a pointer to a class when dealing with Polymorphism?
1 2 3 4 5 6 7 8 9 10 11 12 13 14
|
//class A:
virtual string toString(){/*Do stuff*/}
//class B:
virtual string toString(){ /*Do stuff*/}
//int main:
vector<Employee*> vctr;
vctr.push_back(&employee1);
vctr.push_back(&employee2);
for (int i = 0; i < vctr.size(); ++i)
{
cout <<vctr[i]->toString() << endl;
}
|
Last edited on
Because only pointers or references preserve actual type of underlying object.
Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
|
#include <iostream>
struct foo
{
virtual void baz() {std::cout << "foo\n";}
};
struct bar: foo
{
virtual void baz() {std::cout << "bar\n";}
};
int main()
{
bar y;
//Objects:
foo o = y; //Slicing occurs here
o.baz(); //foo
//pointers
foo* p = &y;
p -> baz(); //bar
//references
foo& r = y;
r.baz(); //bar
}
|
foo
bar
bar |
Last edited on
Topic archived. No new replies allowed.