0
class Parent;
class Child;

Parent *parent;

ifstream inf("file.csv");
inf >> *parent;

//in parent class
friend istream& operator>> (istream &is, Parent &parent) {
  return parent.read(is);
}

virtual istream& read(istream &is){
  char temp[80];
  is >> temp;
  // then break temp into strings and assign them to values
  return is;
}

//virtual istream& read

It reads and assigns only first two values to the Parent class.Child class has Parent class values + 3 of its own.

How can I call I call parent's read() function and then child's read() function so parent's function reads first 2 fields in the file and child reads next 3 fields?

I know it's a matter of syntax; I just can't figure how to do that. I have tried calling Parent::read(is) inside the child read class, I've tried calling it before the child's read(); I have tried read(is) >> temp but none of them worked. When I called Parent::read(is) and then is >> temp, parent is would return all 5 values of the file.

3
  • 1
    all your a,b,c,d,e,g,df,ds,vd,bn variables.. this is bad style. please, write something like this: in_file (can't understand, but suppose it is input file) or input_file or inputFile or etc... Jun 4, 2012 at 9:17
  • IIRC Parent::method() should work.
    – rossum
    Jun 4, 2012 at 10:20
  • I think that Parent::method() would only invoke a static method of Parent. To invoke the Parent version of read I think you'd need to cast your Child to Parent and then invoke read via the Parent ref, as in Child c; Parent(c).read() /* should invoke Parent method */; c.read() /* should invoke Child method */;. I'm assuming here that Child inherits from Parent although the declarations in the question didn't indicate that. Jun 4, 2012 at 10:53

1 Answer 1

1

In this kind of situation you typically have Child override the read function in Parent. This allows the derived class to call the original function in the parent prior to applying it's own logic.

class Parent
{
public:
    virtual void read(istream &s)
    {
        s >> value1;
        s >> value2;
    }
};

class Child : public Parent
{
public:
    virtual void read(istream &s)
    {
        Parent::read(s);  // Read the values for the parent

        // Read in the 3 values for Child
        s >> value3;
        s >> value4;
        s >> value5;
    }
};

To perform a read operation"

// Instantiate an instance of the derived class
Parent *parent(new Child);

// Call the read function. This will call Child::read() which in turn will
// call Parent::read() 
parent->read(instream);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.