CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2
  1. #1
    Join Date
    Feb 2010
    Posts
    1

    Returning a derived class object via a base class reference

    Hi all,

    I'm pretty new to C++ and wondering how i might achieve the following.

    I have a base class with 4 derived classes.

    In my main() i call a read function as part of a user defined file class which reads blocks of text from a file until the end. The 4 derived classes each match 4 different formats of these blocks of text. However, i don't know the format until i've read the first line of each block.

    What i'd like is to be able to define the read function as follows:

    read( base1 objB1)

    but somehow return an object (or pointer to object) of one of the derived class objects.

    Instead i currently have it return a flag to the main() and then in the main i call the relevant readj which matches the 4 different formats. This is too many lines of code in the main for my liking and so i'd prefer to keep the format selection within the main read function.

    Is this possible?

    Further, i'd like to create an array of all the return objects, no matter their format, can i do this and preserve the derived class data (i.e. an array of pointers to the base class, but whose elements actually point to memory with the stored dervied class data?)

    Thanks in advance...

  2. #2
    Lindley is offline Elite Member Power Poster
    Join Date
    Oct 2007
    Location
    Seattle, WA
    Posts
    10,895

    Re: Returning a derived class object via a base class reference

    I did something similar recently. I ended up using a factory pattern, which seemed to work well:
    Code:
    shared_ptr<Base> BaseFactory::construct(istream &in);
    If you use a std::tr1::shared_ptr (or boost::shared_ptr) rather than a raw pointer, it's even easier because you don't have to worry about explicitly freeing the newly allocated object.

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured