Here's the definition of an abstract class:
#include <iostream>
class IStreamable {
public:
virtual void read(std::istream& is) = 0; virtual void write(std::ostream& os) const = 0; };
std::istream& operator>>(std::istream& is, IStreamable& s);
s.read(is);
return is;
}
std::ostream& operator<<(std::ostream& os, const IStreamable& s);
s.write(os);
return os;
}
This class defines, not the structure of a class, but a particular behaviour: any class that is derived from it and implements the abstract methods can interact with streams just like any of the built-in types.
For instance consider this class:
#include"IStreamable.h" // make sure you've set your include path!
class MyData : public IStreamable {
private:
int myint;
double mydouble;
char mychar;
public:
MyData(int i, double d, char c) : myint(i), mydouble(d), mychar(c) {}
virtual void read(std::istream& is);
virtual void write(std::ostream& os) const;
};
void MyData::read(std::istream& is) {
is >> myint >> mydouble >> mychar;
}
void MyData::write(std::ostream& os) const {
os << myint << ' ' << mydouble << ' ' << mychar;
}
Now, if you instantiate an object of class MyData, you can easily stream it any way you like, but there is no point instantiating IStreamable, as it has neither data elements to stream, nor the function implementation required to make it work:
#include "MyData.h"
int main() {
MyData a(3, 3.14, 'p'); std::cout << a << std::endl; return 0;
}
As you can see it doesn't make sense to create an instance of
IStreamable
, and, to add insult to injury, the compiler cannot possibly do that either, as it cannot find any member function definitions.