disclaimer: i'm long time c programmer moving c++, it's likely/possible there better way this.
i create class a 1 n members of class b. in cases, i'm fine calling class b's member functions. however, in cases override member function in class b. there elegant way without having create derived class class b every time?
here example:
using namespace std; #include <iostream> class b { public: void print(); }; void b::print() { cout << "b::print" << endl; } class { public: b b; b bprime; }; int main() { a; a.b.print(); a.bprime.print(); return 0; } is there way override print() function in bprime or otherwise change it? in c, have left class b struct , used function pointers, i'd avoid here.
you can use std::function simulate polymorphism.
class b { public: std::function<_function_signature_here_> print; }; then can override print member in instance of b
a.bprime.print = someotherfunctionwithsamesignature; and moment on bprime behave if different subclass in hierarchy. work same, except particular function changed.
of course have set initial behavior of print member in constructor.
Comments
Post a Comment