Reputation: 6924
I have an abstract class supposed to be an interface, like this:
class IDataSource
{
public:
virtual double getMeThatDouble() = 0;
}
and some implementations like
class IDataSourceStreamer
{
public:
double getMeThatDouble()
{
//implementation
}
}
The point is that I want to use it as initial parameter in constructor of other classes like
class DataNeeder
{
public:
explicit DataNeeder(IDataSource);
}
and here comes the trouble - "parameter of abstract class type is not allowed"
.
I understand that it's forbidden for particular reason - using abstract class by itself is impossible. So what should I do? Is a method like
IDataSource.FeedThat(DataNeeder)
an only option? Kinda ugly.
Upvotes: 2
Views: 3442
Reputation: 90422
You need to pass the abstract type as either a reference or a pointer. For example:
class DataNeeder {
public:
explicit DataNeeder(IDataSource &source) : source_(source) {
}
void someMethod() {
double x = source_.getMeThatDouble();
// ...
}
private:
IDataSource &source_;
}
Then you can have DataNeeder
's member functions operate on source_
. As I mentioned, you can also use a pointer for this task, but I like to only use pointers for "OUT" parameters and things that can conceivable be NULL
.
Upvotes: 11