Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ : Calling a child method from parent instantiation

In my code, I have these classes implemented :

class A
{
  public:
    virtual int fun() { return 0; }
}

class B : public A
{
  public:
    virtual int fun() { return 1; }
}

And these functions :

void operation(A a)
{
  printf("%d\n",a.fun());
}

int main()
{
  B b;
  operation(b);
  return 0;
}

As you can see, the class B inherits of A, and implements the virtual inherited method fun(). The main class calls a function that takes a A in parameters and calls the fun() method, with a B object in argument.

At the execution, I expect the string "1" to be printed, but it's "0" that is (even if it's a B object that is passed to operation()).

I need to do this because I have several B classes (B1, B2, etc...) and I want the function operation() to be generic. I don't need the implementation of operation() in the class A, but if I declare operation() pure virtual, the compilation fails at operation() saying that I can't instantiate A (it's quite expected).

I've found many topic talking about parent/child methods calls and inheritance, but none of them talked about this problem precisely.

Can someone help me ?

Thanks.

like image 384
Senua Avatar asked Feb 07 '14 10:02

Senua


1 Answers

You need to pass the object by reference or pass a pointer

void operation(A& a)

Because you're passing by value, the derived object gets sliced - a new object of type A is created in the scope of the function.

like image 77
Luchian Grigore Avatar answered Sep 18 '22 16:09

Luchian Grigore