Vector container and static binding in C++?

126 views Asked by At

Can someone please explain why i->value() and (i + 1)->value() prints 1 and 3 not 1 and 4 like x[0]->value() << x[1]->value()

#include <iostream>
#include <vector>

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

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

protected:
    int m_n;
};

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

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

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

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

    return 0;
}

Thank you

2

There are 2 answers

1
Igor Tandetnik On BEST ANSWER

y.push_back(b); creates an instance of A which is a copy of the A subobject in b, and pushes that onto the vector. There are no instances of B on the vector, nor could there be, so B::value() is not called. Read about object slicing

0
4pie0 On
void push_back (const value_type& val);

will create an A copy of val if the vector is defined as std::vector<A> V. You see here so called slicing problem. This is why you should use

std::vector<A*> V

or

std::vector<shared_ptr<A> > V