I've got the following code snippet:
class Base{
public:
virtual float operator()(float x){return x;};
};
class Child: public Base{
public:
virtual float operator()(float x) override{return 2 * x;};
};
void scoped(Base b){
std::cout << "Nested: " << b(5) << "\n";
}
int main() {
Child c = Child();
std::cout << "Output: " << c(10) << std::endl ;
scoped(c);
}
The output
20 // expected
5 // unexpected. Should ahve been doubled?
context
I'm making scoped
take a base class because I've got multiple child classes derived from it. On one hand I suppose it makes sense that it would called the ()
from the base class since that's what the type is declared as. On the other hand, why wouldn't it call the method from the instance (which is a Child
first, then a Base
?)
Questions
-
Am I missing something? How would I accomplish what I'm aiming to do? I get the feeling that templates may be a solution but maybe are not the right one?
-
Why is it calling the base class method as opposed to the child
Aucun commentaire:
Enregistrer un commentaire