Search code examples
segmentation-faultvirtualistream

seg fault on virtual istream& function return statement


In main() I have headers: iostream, fstream, iomanip, MyClass.h

char temp;
MyClass *class1;
ifstream inf("file")
while(inf >> temp)
{ 
    if(temp == 'A') class1 = new Myclass();
    inf >> *class1; 
}

In Myclass.h:

class MyClass{
  int num;
protected:
  virtual istream& read(istream &is)
  { /* char temp; is >> temp >> num; */ 
    return is; //seg faults on this line I believe
  } 
public:
  friend istream& operator >> (istream &is, MyClass &class1) {return class1.read(is);}
};

Program should read a file, see if it begins with 'a', then create a class, and parse info into it. Then MyClass passes istream to the read function, that's where I have a seg fault. Program seg faults just as it's going into the while loop. If I remove virtual read function, it doesn't seg fault. gdb just points to 0x000000001 in ??

It's a homework problem, and I need to write body for read() (and other) functions.


Solution

  • The problem is solved now! For time being I worked with those functions without 'virtual' in declaration. When I derived child class from the MyClass, I put 'virtual' back and everything worked fine!