问题
My base class:
class Item
{
protected:
int count;
string model_name;
int item_number;
public:
Item();
void input();
}
My derived Class:
class Bed : public Item
{
private:
string frame;
string frameColour;
string mattress;
public:
Bed();
void input();
}
for now all my input function is trying to do is output which method is being used:
void Item::input()
{
cout<<"Item input"<<endl;
}
void Bed::input()
{
cout<<" Bed Input"<<endl;
}
when I call the function in main I'd like the derived class input to be used but at present the item input is.
Main:
vector<Item> v;
Item* item;
item= new Bed;
v.push_back(*item);
v[count].input();
count++;
I have followed the method laid out in a book I have but I think i may be confused about how to create new objects stored in the vector.
Any help would be great, Thanks Hx
回答1:
You haven't marked your method as virtual
.
Also, because you have a vector
of objects, not pointers, you'll run into object slicing. Although it will compile, it isn't correct.
The proper way is having a vector of pointers or smart pointers.
class Item
{
//....
virtual void input(); //mark method virtual in base class
};
class Bed : public Item
{
//....
virtual void input();
};
vector<Item*> v;
Item* item = new Bed;
v.push_back(item);
//...
//remember to free the memory
for ( int i = 0 ; i < v.size() ; i++ )
delete v[i];
回答2:
In base class:
virtual void input();
In derive class
virtual void input() override;
回答3:
To avoid object slicing you could either use pointers or references. For the behaviour you're looking for, you must declare the function as virtual
in the base class.
Sometimes people prefer tu place the virtual keyword in the derived classes as well, to remember the user that the function is virtual, but that's not mandatory.
You should remember as well that using virtual functions has a cost and you should think about it before actually using it.
来源:https://stackoverflow.com/questions/10351570/polymorphism-inheritance-not-overriding-base-class-method