Saturday, 15 August 2015

c++ - Tricky Polymorphism and virtual functions -



c++ - Tricky Polymorphism and virtual functions -

i have next code.

#include <iostream> using namespace std; class k { public: virtual void add_st(k* n) { cout << "add_st (k*) k\n"; } }; class l: public k { public: virtual void add_st(l* a) { cout << "add_st (l*) l\n"; } }; int main() { l ob, ob2; k k, *pl = &ob; pl->add_st(&ob2); homecoming 0; }

the output of programme be:

add_st (k*) k

the reason why if didn't miss virtual function table. object generated top of hierarchy downwards lowest class.

but code:

#include <iostream> using namespace std; class k { public: virtual void add_st() { cout << "add_st (k*) k\n"; } }; class l: public k { public: virtual void add_st() { cout << "add_st (l*) l\n"; } }; int main() { l ob, ob2; k k, *pl = &ob; pl->add_st(); homecoming 0; }

will print

add_st (l*) l

why?

virtual functions invariant on argument list, , covariant on homecoming type.

an simple way think of virtual fellow member function introduced in base of operations class, defines contract.

for example, given

struct k { virtual k* add_st(k* n); };

the contract add_st accepts object of type k (by pointer), , returns object of type k (by pointer).

this override it

struct l : k { virtual k* add_st(k* a); };

because contract met, , will:

struct m : k { virtual m* add_st(k* a); };

because homecoming object of type m, inheritance object of type k; contract satisfied.

but (the case in question) not override

struct n : k { virtual k* add_st(n* a); };

because cannot take any object of type k, ones both type k , type n. , neither this:

struct p : k { virtual k* add_st(void* a); };

even though type-theoretic perspective, contravariant parameters compatible, truth c++ supports multiple inheritance , upcasts require pointer adjustment, contravariant parameter types break @ implementation level.

they create new function (new slot in v-table) overloads , hides existing function, instead of overriding it. (as john smith says in answer, using-declaration can used avoid hiding base of operations version)

and next error, because signature same, homecoming type incompatible:

struct q : k { virtual void* add_st(k* a); };

here result can object type, that's not enough, contract requires object of type k. , can't override existing function, because parameters don't differ. rejected.

for more details on variance, may want read liskov substitution principle.

c++ polymorphism virtual-functions

No comments:

Post a Comment