C++ Problem: Vectors, Base/Derived classes and output

Status
This thread has been Locked and is not open to further replies. Please start a New Thread if you're having a similar issue. View our Welcome Guide to learn how to use this site.

akidomowri

Thread Starter
Joined
Apr 25, 2003
Messages
52
I will simplify my problem here rather than pasting cose that people might have to comb through.

I have a base class Product. It has several derived classes, CurrentAcct, JuniorAcct, CorporateAcct (It's a bank program!)

Now each customer in the bank has a vector of Products (the base class), in which is stored a number of products (the derived classes).

Now I'm coming to output the Derived classes again (using their own member methods and variables) I've hit a problem with not being able to extract the derived classes from a vector of the base class.

Any advice would be greatly appreciated.

I've tried casting like this:

Product aprod = Products.at(i);
CurrentAcct account;
account = static_cast<CurrentAcct> (aprod);

But I get the conversaion error

T Bear
 
Joined
Aug 12, 2007
Messages
305
I think that you need to use a vector of Product pointers to get that to work. And you need to make sure that the member methods are declared as virtual in the base class. Or at least that's my understanding of the whole inheritance thing.

The problem is that a vector of Products contains memory space for Product size objects. So when you pushback Product-derived objects into the container only the Product-sized stuff fits, the rest of the object is undefined.

I think pointers get around this because the object is stored on the heap, and the vector itself is just full of pointers to objects that are uniform size.
 
Status
This thread has been Locked and is not open to further replies. Please start a New Thread if you're having a similar issue. View our Welcome Guide to learn how to use this site.

Users Who Are Viewing This Thread (Users: 0, Guests: 1)

As Seen On
As Seen On...

Welcome to Tech Support Guy!

Are you looking for the solution to your computer problem? Join our site today to ask your question. This site is completely free -- paid for by advertisers and donations.

If you're not already familiar with forums, watch our Welcome Guide to get started.

Join over 807,865 other people just like you!

Latest posts

Staff online

Top