1
#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);       //create A m_n=1
    const B b(3);       //create B m_n=3

    std::vector<A> V y({a, b});

    V::const_iterator i = y.begin();
    std::cout  << i->f() << (i+1)->f()      //13
              << std::endl;

    return 0;
}

I am trying to understand why the above code prints 13 and not 14. Is it related with implicit copy of m_n of a and b objects? For b object does it copy only from class A members thus getting only the function f() of class A?

BugShotGG
  • 5,008
  • 8
  • 47
  • 63

0 Answers0