mardi 5 mai 2020

How to use value of inherited class member, when upcasting to base class

I have a problem with displaying the content of inherited class members, when up casting to the base class. Currently, the result displayed is 4, how can I achieve 2?

#include <iostream>
#include <vector>
#include <memory>
#include <tuple>

class A {
public:
  A() = default;  
  std::vector<int> v = {3, 4, 5};
};

class B : public A {
public:
    B() { v = {1, 2, 3}; }
    std::vector<int> v = {1, 2, 3};
};

int main() {
   std::vector<std::tuple<std::shared_ptr<A>, int>> v = {
        std::make_tuple<std::shared_ptr<A>, int>(std::make_shared<B>(), 5) 
    };

    std::shared_ptr<A> obj;
    std::tie(obj, std::ignore) = v[0];
    std::cout << obj->v[1] << std::endl;
} 

Aucun commentaire:

Enregistrer un commentaire