0

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

  1. 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?

  2. Why is it calling the base class method as opposed to the child

IanQ
  • 1,831
  • 5
  • 20
  • 29
  • To avoid the object-slicing, change your function to `void scoped(Base & b)` instead. Passing-by-reference avoids the need to copy the object, which avoids the slicing that occurs when copying a `Child` into a `Base` – Jeremy Friesner Nov 13 '20 at 22:22
  • 2
    With `scoped(Base b)`, when you call `scoped(c)`, you create a new (temporary) `Base` object and pass it to function `scoped`. Changing `Base` to `Base&` would tell the compiler that instead of creating that temporary object, it should just pass a reference to the `c` object, whose type is of course `Child`. Of course, the compiler doesn't actually do all of this "runtime stuff" that I just described. But it does generate code which will do exactly that during runtime. – goodvibration Nov 13 '20 at 22:24
  • The parameter to `scoped` is a `Base`. There is no way to pass it an instance of any other class. Also, the code is not `const`-correct, which makes things harder all around. – David Schwartz Nov 13 '20 at 22:46
  • Let me guess, you know Java and are trying to learn C++? This is how objects work in Java, but not in C++. – Sam Varshavchik Nov 13 '20 at 23:01
  • Python, actually. And thanks everyone! I've sorted my code and read through the answer of the other question – IanQ Nov 13 '20 at 23:03

0 Answers0