virtual slicing problem using std::vector<someclass>

  • Thread starter Christian Stigen Larsen
  • Start date
C

Christian Stigen Larsen

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.
 
C

Chris Theis

Christian Stigen Larsen said:
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"

The problem is that the collection triggers the construction of a copy which
is actually stored and thus slicing occurs. As you already mentioned the way
to go is to store pointers.
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();

What exactly do you mean by "anonymous" objects? I don't really see why
storing pointers instead of copies is a problem?

Regards
Chris
 
C

cecconeurale

Christian said:
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.

I'm afraid it is not possible to do anything near what you want, 'cause
doing

v.push_back(child())

with std::vector<parent> is equal to invoke a copy constructor.

The nearest way is doing

v.push_back(new child());

but I think this is even worse than the problem (there's not garbage
collection, it's not Java)
 
C

Christian Stigen Larsen

Quoting cecconeurale <[email protected]>:
| The nearest way is doing
|
| v.push_back(new child());
|
| but I think this is even worse than the problem (there's not garbage
| collection, it's not Java)

Actually, that's a brilliant idea! It was too obvious for me to even
think of it.

I will have to use a gc library though, e.g. Boehm-Weiser, but could possibly
do just as well with a smart-pointer or factory-like approach. Thanks!
 
C

Christian Stigen Larsen

Quoting Chris Theis <[email protected]>:
|> 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();
|
| What exactly do you mean by "anonymous" objects?

Basically, an object that just exists during a call to a function, like:

class Bar;

void foo(const Bar& b) {
//...
}

Calling

foo(Bar())

will produce an object Bar with no name, and its scope ends when foo() returns.

That's what I meant with "anonymous object", although I'm uncertain that's the
correct term.

| I don't really see why storing pointers instead of copies is a problem?

In short, I am writing a parser library, and just wanted a specific interface
for users.

After considering the insightful comments in this thread I've decided that
pointers actually *is* the way to go. Again, thanks!
 
K

Karl Heinz Buchegger

Christian said:
Quoting Chris Theis <[email protected]>:
|> 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();
|
| What exactly do you mean by "anonymous" objects?

Basically, an object that just exists during a call to a function, like:

class Bar;

void foo(const Bar& b) {
//...
}

Calling

foo(Bar())

will produce an object Bar with no name, and its scope ends when foo() returns.

Usually this is called a 'temporary object'
 
C

Chris Theis

Christian Stigen Larsen said:
Quoting cecconeurale <[email protected]>:
| The nearest way is doing
|
| v.push_back(new child());
|
| but I think this is even worse than the problem (there's not garbage
| collection, it's not Java)

Actually, that's a brilliant idea! It was too obvious for me to even
think of it.

IMHO the introduction of a full blown sophistacted concept like a garbage
collection just to avoid slicing is not such a hot idea. In some cases it's
even better to store pointers instead of copies because this will reduce
unnecessary object duplication.
I will have to use a gc library though, e.g. Boehm-Weiser, but could possibly
do just as well with a smart-pointer or factory-like approach. Thanks!

In case you want somebody else to take care of deleting the objects you
created on the heap you can certainly stick to smart_pointers.

Regards
Chris
 
C

Chris Theis

cecconeurale said:
Christian Stigen Larsen wrote:
[SNIP]

I'm afraid it is not possible to do anything near what you want, 'cause
doing

v.push_back(child())

with std::vector<parent> is equal to invoke a copy constructor.

The nearest way is doing

v.push_back(new child());

but I think this is even worse than the problem

It's at least one step further towards memory or resource leaks.
(there's not garbage
collection, it's not Java)

Well, what's the need for a garbage collection in this case? C++ supplies
the keyword delete which perfectly fulfills the need to clean up. I don't
want this to become a discussion about the advantages/disadvantages of
garbage collections but this simple problem can certainly be accomplished
without one.

Chris
 
E

Eric

Perhaps you can store a smart pointer in the vector which will give
you the right polymorphic behaviour and perform the cleanup.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top