CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 15 of 16

Threaded View

  1. #3
    Join Date
    Apr 1999
    Posts
    27,449

    Re: Write file of base objects into vector of derived objects

    Quote Originally Posted by cbpetro View Post
    I have a binary file that I have written base objects. I want to read those base objects into a vector of objects that I have derived from base.
    First, a vector<CDerived> can only hold CDerived objects safely -- it should not hold CBase objects, even if CDerived is a derived class of CBase. In general, a vector<T> can only hold T objects. It cannot hold any other type, even if the other type is derived from T. Trying to hod other types in a vector that is meant to hold a certain type leads to undefined behaviour, even if the program compiles. The call to fwrite() that you're using breaks this rule.

    Second, your base class has a virtual destructor, making the class non-POD. In C++, you can't wipe out or populate non-POD objects using low-level functions such as fwrite(), memcpy(), memset(), etc. These functions rip your non-POD types to shreds, making them unusable and unstable. Instead, you create or set these object's members using proper construction of the objects, and calling the public member functions of the object, nothing else.

    So as monarch_dodra suggested, you write each member of the object to a file in a way so that when it comes time to read the file, you can recreate the object from the contents of the file. The easiest way to do this is to write an operator << for your class to do output, and an operator >> for input.

    Regards,

    Paul McKenzie
    Last edited by Paul McKenzie; July 20th, 2011 at 05:28 AM.

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