1. Computer problem? Tech Support Guy is completely free -- paid for by advertisers and donations. Click here to join today! If you're new to Tech Support Guy, we highly recommend that you visit our Guide for New Members.

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

Discussion in 'Software Development' started by akidomowri, Mar 25, 2008.

Thread Status:
Not open for further replies.
  1. akidomowri

    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
     
  2. burnthepc

    burnthepc

    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.
     
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 733,556 other people just like you!

Loading...
Similar Threads - Problem Vectors Base
  1. n00e
    Replies:
    2
    Views:
    377
Thread Status:
Not open for further replies.

Short URL to this thread: https://techguy.org/697146

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice