Home Ask Login Register

Developers Planet

Your answer is one click away!

Faddev February 2016

Fail to push_back() derived class into STL list in C++

I would appreciate any help with this.

The problem is that I can not successfully push_back something into a STL list. Here are details:

Fo is a abstract class and Foo is a class inherit from Fo. f0, f1 are instances of the class Foo. fooList has type std::list<Foo> and foList has type std::list<Fo*>.

When I try fooList.push_back(f1); I can cout the value for member p, but can not call function test(); When I try foList.push_back(&f1); I even can not cout the value for member p, let alone call function test().

With lines with error-1/2/3 commented, I obtained the output:

Fo constructor
Foo constructor
Fo constructor
Foo initialization 
Fo constructor
Foo copy constructor
inside fooList :11

I also realize foList.push_back(&f1) did not call Foo copy constructor, which may be relevant for error-2.

When I try to call function test() in fooList, I obtain an error msg:

error: member function 'test' not viable: 'this' argument has type
  'const Foo', but function is not marked const

When I try to cout member p in foList, I obtain an error msg:

error: no member named 'p' in 'Fo'

I have no idea how to fix the problem.

Thanks a lot!

Full code list below:

#include <iostream>
#include <list>

class Fo
    Fo() { std::cout << "Fo constructor" << std::endl; }
    Fo(const Fo& f) { std::cout << "Fo copy constructor" << std::endl; }
    virtual ~Fo(){};
    virtual void test()=0;

class Foo : public Fo
    int p;


oklas February 2016

To fix

//std::cout<<"inside fooList :"<<i->p<<" and "<<i->test();  // error-1


std::list<Foo>::const_iterator i=fooList.begin();


std::list<Foo>::iterator i=fooList.begin();

To fix

//std::cout<<(*it)->p<<std::endl;  // error-2

replace with

std::cout<<(Foo*(*it))->p<<std::endl;  // error-2

To fix:

//std::cout<<"inside foList :"<<(*it)->p<<" and "<<it->test();  // error-3


//std::cout<<"inside foList :"<<(Foo*(*it))->p<<" and "<<it->test();  // error-3

Post Status

Asked in February 2016
Viewed 1,812 times
Voted 6
Answered 1 times


Leave an answer

Quote of the day: live life