0
#include <iostream>

using namespace std;

struct A
{
    virtual int func(void) { return 0; }
};

struct B : A
{
    int func(void) { return 1; }
};

int main()
{
    A b = B();
    cout << b.func() << endl;
}

I was expecting the output to be 1 but as most of you will know its 0.

what i want to achieve in my actual code is something along these lines.

struct A
{
     virtual int operator() (int i);
};
struct B : A
{
     int operator() (int i) { return i*2; }
};
struct C : A
{
     int operator() (int i) { return i*3; }
};
struct x
{
     A test;
};

So my container won't be able to tell before hand if it will hold a A, B or C, but should behave differently still.

Is there a way to achieve the functionality as I anticipated it work??

user2255757
  • 756
  • 1
  • 6
  • 24

2 Answers2

4

A b = B();: you're constructing an object of type A, using the assignment operator/copy constructor (through copy elision) from a B object, but seen as a reference to A (which explains why it compiles without errors)

This isn't polymorphism. b is still of type A. The link to B has been lost.

That would do it:

A *b = new B();

now

cout << b->func() << endl;

triggers polymorphism/virtual function and yields 1 as expected.

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
  • thanks man, but is there no way of achieving this without pointers? the parent and child objects are all going to be just a class containing functions, no variable members or anything. – user2255757 Dec 23 '16 at 22:32
  • There is no way without pointers or references. – user6556709 Dec 23 '16 at 22:35
2

C++ virtual functions only works for references/pointers, which means indirections.

A b = B();

This creates an object of type A, not of type B. No indirection, therefor only the function in A is called.

user6556709
  • 1,272
  • 8
  • 13