The problem is that you pass const A& , but add not const , if you remove the const modifier, then this works:
int f(A& base_class) {
I am using gcc , and an error that really tells you what is happening:
error: no matching function for call to 'A::add(int&) const' base_class.add(a); ^^^^^ no known conversion for implicit 'this' parameter from 'const A*' to 'A*' ^^^^^^^^
Based on your answer, another option is make m_i mutable and make const member methods as follows:
class A { public: A(int val): m_i(val) { } virtual void add(int i) const = 0; protected: mutable int m_i; }; class B: public A { public: B(int val): A(val) { } B(): A(0) { } virtual void add(int i) const { m_i += i; } }; class C: public A { public: C(int val): A(val) { } C(): A(0) { } virtual void add(int i) const { m_i += i*2; } }; int f(const A& base_class) { base_class.add(5) ;
source share