Source type not polymorphic
I want to be able to add the functionality (somehow) in red. Any ideas?
Code:
#include <iostream>
struct Foo{
public:
int getInt(){ return mInt; }
protected:
int mInt;
friend class FooModifier;
};
class Bar : public Foo{
public:
char getChar(){ return mChar; }
private:
char mChar;
friend class FooModifier;
};
class FooModifier{
public:
FooModifier( Foo* f )
: mFoo( f ){}
void setInt( int n ){ mFoo->mInt = n; }
void setChar( char c ){ dynamic_cast<Bar*>(mFoo)->mChar = c; } // Source of problem
private:
Foo* mFoo;
};
int main(){
Foo* f = new Foo();
FooModifier fm(f);
fm.setInt(5);
std::cout << f->getInt() << "\n";
Bar* b = new Bar();
FooModifier fm2( dynamic_cast<Foo*>(b) );
fm2.setInt(7);
std::cout << b->getInt() << "\n";
// Want to be able to modify both foo and bars
fm2.setChar('k');
std::cout << b->getChar() << "\n";
return 0;
}