class - c++ how to call function with subclass, having superclass pointer -
i have 3 classes, a, b , c:
class { public: virtual bool sm(b b) = 0; virtual bool sm(c c) = 0; }; class b : public { bool sm(b b) { //code } bool sm(c c) { //code } }; class c : public { bool sm(b b) { //code } bool sm(c c) { //code } };
and vector<a*> objects
, stores b or c objects. (for example generates randomly)
can call somehow
for(int = 0; < objects.size(); i++) { for(int j = i; j < objects.size(); j++) { objects[i].sm(objects[j]); } }
without dynamic cast or something? because there can bit more of b-c classes
, bag thing, , may there better way it?
solution
odelande
said , understood, solution problem
#include <iostream> #include <vector> class b; class c; class { public: virtual bool sm(a* a) = 0; virtual bool sm(b* b) = 0; virtual bool sm(c* c) = 0; }; class b : public { public: bool sm(a* a) { return a->sm(this); } bool sm(b* b) { std::cout << "in b doing b" << std::endl; return true; } bool sm(c* c) { std::cout << "in b doing c" << std::endl; return false; } }; class c : public { public: bool sm(a* a) { return a->sm(this); } bool sm(b* b) { std::cout << "in c doing b" << std::endl; return true; } bool sm(c* c) { std::cout << "in c doing c" << std::endl; return false; } }; int main() { std::vector<a*> objects; objects.push_back(new b()); objects.push_back(new c()); objects[0]->sm(objects[0]); objects[0]->sm(objects[1]); objects[1]->sm(objects[0]); objects[1]->sm(objects[1]); std::cin.get(); return 0; }
this code outputs
in b doing b
in c doing b
in b doing c
in c doing c
you cannot this. overloads of sm()
method statically resolved, i.e. @ compile time (besides, sm()
should take pointers b
, c
). compiler knows objects[j]
a*
; cannot resolve call because there no overload takes a*
input.
what want dispatch call based on runtime type of objects[j]
. call virtual function does. so, should have 1 sm()
method, should in turn call virtual method of argument.
Comments
Post a Comment