virtual slicing problem using std::vector<someclass>

From: Christian Stigen Larsen (cslarsen_at_newscache.ntnu.no)
Date: 11/21/03


Date: Fri, 21 Nov 2003 10:17:16 +0000 (UTC)

Consider the following:

  class parent {
  public:
    virtual void print() {
      printf("Parent\n");
    }
  };

  class child : public parent {
  public:
    void print() {
      printf("Child\n");
    }
  };

My problem is that I want to use a container class (preferrably std::vector) to
contain ``parent''-objects. When I pass a ``child''-object to push_back()
slicing occurs:

  child c;
  std::vector<parent> v;
  v.push_back(c);
  v[0].print(); // produces "Parent\n", instead of "Child\n".

I troved the FAQ and found that my problem is directly related to item 31.8:

http://www.parashift.com/c++-faq-lite/value-vs-ref-semantics.html#faq-31.8

So one way of resolving this situation is to store pointers in the vector:

  std::vector<parent*> v;
  v.push_back(&c);
  v[0]->print(); // produces "Child\n"

In my case, this is inconvenient, since I want to be able to use ``anonymous
objects'' (IIRC, that's the correct term):

  v.push_back(child());
  v[0].print();

Any suggestions what to do in my case? Seems I'm at an impasse, possibly
leading to a design decision about my code, but I wanted to check with you
guys first.

-- 
Christian Stigen Larsen -- http://csl.sublevel3.org


Relevant Pages