AlgoRythm
AlgoRythm

Reputation: 1389

struct not inheriting virtual function

I have two structs which inherit from each other, and a parent struct which has no relation to these structs but manages a std::vector of pointers for the main class. Here's some code.

Parent class definition:

struct Widget {
    virtual void inflate();
}

Child class definition:

struct Label : public Widget {
    void inflate();
}

Function implementations:

void Label::inflate(){
    std::cout << "Child function called" << std::endl;
}

void Widget::inflate(){
    std::cout << "Parent function called" << std::endl;
}

Usage:

std::vector<Widget*> widgets = std::vector<Widget*>();
Label1 = Label();
Label2 = Label();
widgets.push_back(Label1);
widgets.push_back(Label2);
int i = 0;
while(i < widgets.size()){
    widgets[i]->inflate();
    i++;
}

Output:

Parent function called
Parent function called

Thank you

Upvotes: 1

Views: 42

Answers (1)

Patrick Kostjens
Patrick Kostjens

Reputation: 5105

The problem is in your usage code as the comments already said. I've modified it so that it compiles and runs as expected. I can't tell you the exact problem with your original code though as it doesn't compile.

Here is the working code:

#include <iostream>
#include <vector>

struct Widget {
    virtual void inflate();
};

struct Label : public Widget {
    void inflate();
};

void Label::inflate(){
    std::cout << "Child function called" << std::endl;
}

void Widget::inflate(){
    std::cout << "Parent function called" << std::endl;
}

int main()
{
    std::vector<Widget*> widgets = std::vector<Widget*>();
    Label Label1;
    Label Label2;
    widgets.push_back(&Label1);
    widgets.push_back(&Label2);
    int i = 0;
    while(i < widgets.size()){
        widgets[i]->inflate();
        i++;
    }
}

Link to see it work: https://ideone.com/ETDClF

Upvotes: 2

Related Questions