0
#include <iostream>
#include <list>

using namespace std;

class A{
    public:
        A(): data_(0){}
        virtual void print(){
            cout << "no" << endl;
        }
    protected:
        int data_;
};
class B : public A{
    public:
        B(): A(){}
        void print() override{
            cout << data_ << endl;
        }
};


list<A> my;

int main()
{

    B* b = new B();
    b->print();

    my.push_back(*b);
    for (list<A>::iterator i = my.begin(); i != my.end(); i++){
        i->print();
    }

}

The result of b->print is 0, but why is the result of i->print() no?

I want to make 0 come out when I use STL lists and polymorphism. What should I do?

Marcus Müller
  • 34,677
  • 4
  • 53
  • 94
Atoro
  • 11
  • 1
  • 1
    The direct answer is that to use polymorphism in C++, you need to use a pointer or reference to the actual object. In your case, you'll probably want a list of pointers rather than a list of objects. Most of the time that should probably be some smart pointer class rather than raw pointers. You might also want to look into Boost [ptr_list](https://www.boost.org/doc/libs/1_37_0/libs/ptr_container/doc/ptr_list.html). – Jerry Coffin Nov 22 '21 at 16:53
  • Thank you! I need to study hard. – Atoro Nov 22 '21 at 17:11

0 Answers0