Question

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

Was it helpful?

Solution

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

OTHER TIPS

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top