473,748 Members | 4,697 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

virtual slicing problem using std::vector<som eclass>

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<par ent> 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<par ent*> 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(chi ld());
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 5051
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<par ent> 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<par ent*> 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(chi ld());
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(chi ld())

with std::vector<par ent> 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.i t>:
| 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******@newsc ache.ntnu.no> wrote in message
news:sl******** *************@t iger.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<par ent> 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<par ent*> 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(chi ld());
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.c h>:
|> 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(chi ld());
|> 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.c h>:
|> 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(chi ld());
|> 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

"cecconeura le" <fr************ ****@virgilio.i t> wrote in message
news:bp******** **@news.flashne t.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(chi ld())

with std::vector<par ent> 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******@newsc ache.ntnu.no> wrote in message
news:sl******** *************@t iger.stud.ntnu. no...
Quoting cecconeurale <fr************ ****@virgilio.i t>:
| 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******@newsca che.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<par ent> 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<par ent*> 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(chi ld());
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
1481
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 constructor SomeClass() another constructor, SomeClass(int) etc. What then would the values be of the new values being appended via the resize method. Would they be equal to SomeClass() ? In other words, would they be initialized with the...
0
9530
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9363
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9312
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
1
6793
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6073
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4593
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4864
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3300
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2206
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.