2

Here is a sample C++ question to find out the outcome.

#include <iostream>
#include <vector>

class A
{
public:
    A(int n = 0) : m_n(n) { }

public:
    virtual int f() const { return m_n; }
    virtual ~A() { }

protected:
    int m_n;
};

class B
    : public A
{
public:
    B(int n = 0) : A(n) { }

public:
    virtual int f() const { return m_n + 1; }
};

int main()
{
    const A a(1);
    const B b(3);
    const A *x[2] = { &a, &b };
    typedef std::vector<A> V;
    V y({ a, b });
    V::const_iterator i = y.begin();

    std::cout << x[0]->f() << x[1]->f()
              << i->f() << (i + 1)->f() << std::endl;

    return 0;
}

The output I expected was "1 4 1 4" but the correct answer is "1 4 1 3".

From above,

x[0]->f()

i.e., x[0] is nothing but a pointer to an object of type A and calling f() returns 1.

x[1]->f()

i.e., x[1] is nothing but a pointer to an object of type A (base class pointer pointing to derived class object) and calls derived class f() that returns (3 + 1) = 4

I am not sure how this behaves when we add the objects a and b into a vector container and iterating them through const_iterator with inheritance

i->f()

I can understand this as i is just a pointer to the first element i.e., object a.

But what will happen here?

(i + 1)->f()

My understanding is that it points to the next element in the sequence i.e., object b and calling f() through derived class pointer should call its member function rather than base class one's?

Jarod42
  • 203,559
  • 14
  • 181
  • 302

1 Answers1

5

The vector y contains two objects of type A. Not type B. When it is constructed, it makes copies of a and b, slicing b as it does so. So (i + 1)->f() calls A::f() on that copy of the A portion of b, giving 3.

Community
  • 1
  • 1
aschepler
  • 70,891
  • 9
  • 107
  • 161