bemused and confused
bemused and confused

Reputation: 113

Polymorphism inheritance not overriding base class method

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

Upvotes: 1

Views: 4511

Answers (3)

Uflex
Uflex

Reputation: 1426

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.

Upvotes: 0

Luchian Grigore
Luchian Grigore

Reputation: 258618

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];

Upvotes: 5

Zaheer Ahmed
Zaheer Ahmed

Reputation: 28578

In base class:

virtual void input();

In derive class

virtual void input() override;

Upvotes: 0

Related Questions