Reputation: 61
Here is a sample parent and child I'm working with.
class Home{
public:
virtual void input();
virtual void output();
private:
};
class Ocelot : public Home{
public:
void input(istream& ins = cin);
void output(ostream& outs = cout);
private:
int revolvers;
double shadeCover;
int waterSources;
};
And here is my main where I'm trying to make a pointer that can hold different kinds of children and call their functions.
int main(){
list<Home> animals;
Home * ptr;
ptr = new Ocelot;
ptr->input();
ptr->output();
return 0;
}
When I attempt to compile, I'm just getting undefined references to Home::input and Home::output. What exactly is it that I'm doing incorrectly here? Thank you for your time.
Edit: In case it wasn't clear, I am trying to call the Ocelot input and output functions. The Home ones don't exist.
Upvotes: 0
Views: 99
Reputation: 3288
If Home::input
and Home::output
don't require implementations, make them pure virtual functions:
virtual void input() = 0;
virtual void output() = 0;
Otherwise, you need to define an implementation for them in Home
so the linker doesn't complain about it:
virtual void input() { /* code */ }
virtual void output() { /* code */ }
You will also need to make the signatures of input
and output
the same for the base class Home
and derived class Ocelot
. Either add the stream parameters to the signatures of Home::input
and Home::output
or remove them from Ocelot::input
and Ocelot::output
.
Additionally: list<Home>
will cause problems for you; you will need to use list<Home*>
instead so the base class (which is now abstract because of the pure virtual functions) is not being instantiated.
Upvotes: 3
Reputation: 29332
list animals;
You cannot do this if Home
is an abstract class. std containers cannot hold abstract classes (interfaces), simply because these cannot be constructed or instanciated. What you can do is:
list<Home*> animals;
Apart from this, make your input()
and output()
methods pure virtual (=0;
) and do implement them in child classes that inherit the Home
interface.
Upvotes: 0