As the title states, I want to be able to print 101 in the following code:
#include <iostream>
#include <sstream>
#include <string>
class A {
public:
virtual int num(); // Method I want to override
std::string str();
};
class B: public A {
public:
int num();
};
int A::num(){
return 0; // default value
}
std::string A::str(){
std::ostringstream s;
s << num();
return s.str();
}
int B::num(){
return 101; // overriden value
}
int main(){
B b;
A a = b; // Upcast
std::cerr << a.str() << std::endl; // Want to print 101, but print 0
return 0;
}
In the general case, I have multiple subclasses of of a parent (A
) that implement their own logic for calculating something (num()
), and the parent performs the same stuff on the output of that something (str()
) for all different implementations of num()
. I couldn't figure out how to do this in c++.
I come from a python background and am still learning c++. Normally this would work in python, but if this isn't a good design or not the right OOP way of doing this, feel free to offer an alternative solution that doesn't involve inheritance.