user2990428
user2990428

Reputation: 31

C++ Access Violation while Reading from File

Just starting out on C++.

I am getting access violation errors while reading from a binary file. Here are the classes involved:

class Staff { //base class
public:
    Staff() {}
    virtual ~Staff{}
}

One of the derived classes:

class Scheduler : public Staff {
public:
    Scheduler() {}
    //no destructor defined
}

And then in code that uses these classes:

ifstream in("Scheduler.dat", ios::in | ios::binary);
Scheduler s;
in.read(reinterpret_cast<char *>(&s), sizeof(Scheduler));

The moment I hit the read statement, the access violation exception triggers, and VS2013 points to the virtual destructor in class Staff.

Is it because I didn't explicitly create a destructor in class Scheduler? Or is it caused by something else?

Upvotes: 1

Views: 421

Answers (1)

user657267
user657267

Reputation: 21000

Scheduler is not a trivially copyable class, you cannot read from or write it bytewise to a file like this.

http://en.cppreference.com/w/cpp/types/is_trivially_copyable

A trivially copyable class is a class that

  1. Has no non-trivial copy constructors (this also requires no virtual functions or virtual bases)
  2. Has no non-trivial move constructors
  3. Has no non-trivial copy assignment operators
  4. Has no non-trivial move assignment operators
  5. Has a trivial destructor

You'll either have to remove the virtual destructor (which brings its own set of issues if you want to use Staff polymorphically), read and write to the file using a serialization library, or write your own serialization function, the canonical way would be something like std::ostream& operator<<(std::ostream&, Staff const&);

Upvotes: 4

Related Questions