-1
#include <iostream>
#include <vector>
using std::cout;
using std::cin;
using std::endl;

class base {
    int data;
public:
    base(int d = 100) : data(d) {}
    virtual int getData() const {return data;}
};

class derived : public base {
    int dData;
public:
    derived(int dd = 32) : base(), dData(dd) {}
    virtual ~derived(){}
    int getData() const {return dData;}
};



int main(){
    std::vector<base> vec;
    base A(20);
    derived B(32);

    vec.push_back(A);
    vec.push_back(B);

    for(unsigned int i=0; i < vec.size(); i++)
        cout << "vector[" << i << "] :" << vec[i].getData() << endl;

    base * ptr;
    ptr = &A;
    cout << "Base pointing: " << ptr->getData() << endl;

    ptr = &B;
    cout << "Derived pointing: " << ptr->getData() << endl;

}

Above the code,i create a vector which is type of base and put a derived object in it. when i try to read the values i cant get the correct ones. Even though i put 'virtual' statement before the function which has the same name in my classes. But in pointer way there is no problem.

here is the output of code.

vector[0] :20
vector[1] :100
Base pointing: 20
Derived pointing: 32

1 Answers1

0
int main(){
    std::vector<base *> vec;
    base A(20);
    derived B(32);

    vec.push_back(&A);
    vec.push_back(&B);

    for(unsigned int i=0; i < vec.size(); i++)
        cout << "vector[" << i << "] :" << vec[i]->getData() << endl;

    base * ptr;
    ptr = &A;
    cout << "Base pointing: " << ptr->getData() << endl;

    ptr = &B;
    cout << "Derived pointing: " << ptr->getData() << endl;

}

Well, when i use pointer base vector, it gives the correct values. Thank you for your answers.