473,238 Members | 1,709 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,238 software developers and data experts.

virtual slicing problem using std::vector<someclass>

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-lit....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
Jul 22 '05 #1
8 5007
Christian Stigen Larsen wrote:
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-lit....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)
Jul 22 '05 #2
Quoting cecconeurale <fr****************@virgilio.it>:
| 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!

--
Christian Stigen Larsen -- http://csl.sublevel3.org
Jul 22 '05 #3

"Christian Stigen Larsen" <cs******@newscache.ntnu.no> wrote in message
news:sl*********************@tiger.stud.ntnu.no...
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-lit....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
Jul 22 '05 #4
Quoting Chris Theis <Ch*************@nospam.cern.ch>:
|> 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!

--
Christian Stigen Larsen -- http://csl.sublevel3.org
Jul 22 '05 #5


Christian Stigen Larsen wrote:

Quoting Chris Theis <Ch*************@nospam.cern.ch>:
|> 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'

--
Karl Heinz Buchegger
kb******@gascad.at
Jul 22 '05 #6

"cecconeurale" <fr****************@virgilio.it> wrote in message
news:bp**********@news.flashnet.it...
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
Jul 22 '05 #7

"Christian Stigen Larsen" <cs******@newscache.ntnu.no> wrote in message
news:sl*********************@tiger.stud.ntnu.no...
Quoting cecconeurale <fr****************@virgilio.it>:
| 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
Jul 22 '05 #8
Perhaps you can store a smart pointer in the vector which will give
you the right polymorphic behaviour and perform the cleanup.

cs******@newscache.ntnu.no (Christian Stigen Larsen) wrote in message news:<sl*********************@tiger.stud.ntnu.no>. ..
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-lit....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.

Jul 22 '05 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
by: pauldepstein | last post by:
Suppose a vector taking elements in SomeClass is resized from length 5 to length 8 using the resize method. SomeClass is a class which takes a variety of constructors SomeClass contains a...
3
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 3 Jan 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). For other local times, please check World Time Buddy In...
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 7 Feb 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:30 (7.30PM). In this month's session, the creator of the excellent VBE...
0
by: fareedcanada | last post by:
Hello I am trying to split number on their count. suppose i have 121314151617 (12cnt) then number should be split like 12,13,14,15,16,17 and if 11314151617 (11cnt) then should be split like...
0
by: stefan129 | last post by:
Hey forum members, I'm exploring options for SSL certificates for multiple domains. Has anyone had experience with multi-domain SSL certificates? Any recommendations on reliable providers or specific...
1
by: davi5007 | last post by:
Hi, Basically, I am trying to automate a field named TraceabilityNo into a web page from an access form. I've got the serial held in the variable strSearchString. How can I get this into the...
0
by: MeoLessi9 | last post by:
I have VirtualBox installed on Windows 11 and now I would like to install Kali on a virtual machine. However, on the official website, I see two options: "Installer images" and "Virtual machines"....
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: Aftab Ahmad | last post by:
Hello Experts! I have written a code in MS Access for a cmd called "WhatsApp Message" to open WhatsApp using that very code but the problem is that it gives a popup message everytime I clicked on...
0
by: Aftab Ahmad | last post by:
So, I have written a code for a cmd called "Send WhatsApp Message" to open and send WhatsApp messaage. The code is given below. Dim IE As Object Set IE =...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.