Save class into a file

I am creating a program using the inheritance. The superclass is person and subclass is employee,manager etc. I will prompt the user to choose which subclass he want to save the record to but i dont know how to write and display the record of different subclass to and from a txt file. May i know is there any example? Thanks a lot.
What I would do is create a polymorphic Save() method in your base class Person that takes a file name as a parameter.

Then, in your inherited classes, provide unique implementation for each class.

In your main, just use a pointer to the base class person and then you can use the same Save() method for any of the derived classes.

For example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
class Person
{
public:
   virtual Save(string filename) = 0;  // this makes it required to implement
};

class Employee : Person
{
public:
    virtual Save(string filename) 
    {
         // implement it for employees
    }
};

class Manager : Person
{
public:
    virtual Save(string filename) 
    {
         // implement it for managers
    }
};


int main( )
{

  Person* p;
  
  p = new Employee;
  p->Save(filename);  // calls employees save method
  delete p;

  p = new Manager;
  p->Save(filename);  // calls managers save method
  delete p;

  return 0;
}

Last edited on
C++ declares members private by default. You'll need to specify that the Save() function is public or at least protected in the base or superclass for this to work.
^^

yea, you're right. I just wrote that out quickly. It just seems like the most logical design to use in this case.

Finally it works.
IceThatJaw and pogrady, thanks a lot=v=
Last edited on
Topic archived. No new replies allowed.