473,387 Members | 1,592 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,387 software developers and data experts.

Accessing subclasses of objects stored in container class.

Hello, I am having trouble with a Polymorphism issue using container classes.

I have a longwinded and shortwinded version of my question:

Shortwinded version:

How can I store base class objects in a container class like a vector or list while still being able to access the individual subclass (virtual) functions? In my program, it is as if the functions aren't virtual.

Longwinded version:

I have a class "Poisson" which has several subclasses (say, "Predator and Prey").

I would like to address specific functions of one of these sublasses without knowing which subclass I'm dealing with.

For a specific instance of the class, I would (for example) do this via:

___________________________________________

Poisson thing1*;
Poisson thing2*;

...

thing1 = new Predator();
thing2 = new Prey();

...

thing1.think(); // calls Predator::think();
thing2.think(); // calls Prey::think();
thing1.move();
thing2.move();

...
___________________________________________


In my program, the elements are stored in some data structure and each program loop cycles through the elements. Since the elements themselves are constantly coming in and out of existence, I'd like to use a linked list type structure to store them. So I thought I'd try using container classes instead of throwing together my own list.

My problem is that when I add these elements to the list, they are all stored as the base class and I can not address the subclass' individual (virtual) functions.

Can anyone help me to understand how to store a <list> or <vector> of objects which inherit a common base class object such that I can address the subclass functions individually? In other words, how can I store a list of objects with the same functionality as the above code?

I've attached some sample code which shows what I'm doing now and the problem that arises.

Thanks for your time!

- Andrew


/* ************************************************** **** **
* Example Code *
************************************************** ******* */

Poisson *herbert;
Poisson *carnie;
Poisson *fernie;


vector<Poisson> vec;

int main(int argc, char *argv[])
{

// Create Objects which are each some subclass of Poisson class.
herbert = new Predator('r',12,42,"Roberto");
carnie = new Prey('y',23,6,"Kate");
fernie = new Tree('y',23,6,"Fern");

// Push objects on to list.
vec.push_back(*herbert);
vec.push_back(*carnie);
vec.push_back(*fernie);

// Cycle through list and reference abstract objects.

unsigned int index;
for (index = 0; index < vec.size(); index++)
{
Poisson *temp = &vec[index];
cout << temp->getName() << endl;
// This returns Poisson::getName() instead of (say) Prey::getName();
}
}
May 28 '07 #1
3 2383
weaknessforcats
9,208 Expert Mod 8TB
Start off by not storing base class objects in your containers.

When you create a Prey and store it as a Poisson, a copy is made using the Poisson copy constructor. None of the Prey is copied. All that's in the container is the base portion of yout Prey object.

This phenomen is call slicing and it's bad news.

You must store Poisson pointers in your container.

Expand|Select|Wrap|Line Numbers
  1. vector<Poisson*> vec;
  2.  
You cannot make copies of your objects.

Further, storing pointers isn't such a good idea either when it comes to memory management. I suggest you read my article on Handle Classes in the C++ Articles section.

Lastly,

Your vector should not be a global variable. It should be local to main().
May 28 '07 #2
Perfect. Made the changes and it works.

I didn't know about this clipping business.

Thanks for the advice!

- Andrew

Start off by not storing base class objects in your containers.

When you create a Prey and store it as a Poisson, a copy is made using the Poisson copy constructor. None of the Prey is copied. All that's in the container is the base portion of yout Prey object.

This phenomen is call slicing and it's bad news.

You must store Poisson pointers in your container.

Expand|Select|Wrap|Line Numbers
  1. vector<Poisson*> vec;
  2.  
You cannot make copies of your objects.

Further, storing pointers isn't such a good idea either when it comes to memory management. I suggest you read my article on Handle Classes in the C++ Articles section.

Lastly,

Your vector should not be a global variable. It should be local to main().
May 28 '07 #3
Can you kindly show the changes in code??? It would help illustrate a lot.
Jun 8 '07 #4

Sign in to post your reply or Sign up for a free account.

Similar topics

8
by: Marco | last post by:
Hi all, I have a base class and some subclasses; I need to define an array of objects from these various subclasses. What I have is something like: { //I have a base class, something like:...
5
by: Jack Addington | last post by:
How do I go about accessing elements of an Arraylist using something other than the index? I have a class that manages a number of subclasses. Those subclasses are stored in an arraylist. The...
3
by: Alex | last post by:
I'm having a problem porting an ASP solution to ASPX. In the ASP solution I'm accessing a DCOM server, create sub DCOM objects and call functions from VB script on the ASP pages. The DCOM object...
9
by: Ric | last post by:
im new to asp.net. please help if u can. is it possible to refer to a control(ie lable, placeholder, textbox) that is inside a repeater object from a code behind file? when i place the control...
12
by: Steve Blinkhorn | last post by:
Does anyone know of a way of accessing and modifying variables declared static within a function from outside that function? Please no homilies on why it's bad practice: the context is very...
9
by: newbie | last post by:
Let's see two different usage of an STL container. I see (2) more often when reading code over (1), dose that give any benefit or it's purely a coding preference? Also, please see the (3), I see...
14
by: Marko | last post by:
I have abstract superclass named Element, and several subclasses derived from it: And, Or, Nand, Nor... I have method which has to take 2 subclasses of element as its parameters types. Can't use ...
19
by: Daniel Pitts | last post by:
I have std::vector<Base *bases; I'd like to do something like: std::for_each(bases.begin(), bases.end(), operator delete); Is it possible without writing an adapter? Is there a better way? Is...
6
by: Bhawna | last post by:
I am into c++ code maintenance for last 3-4 years but recently I am put into design phase of a new project. Being a small comapany I dont have enough guidance from seniors. Currently I am into a...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...
0
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...

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.