0

I have the following classes

Entity

class Entity {
  public:
    virtual std::ostream& write(std::ostream& os) const {
        os << "Can't output Entity";
        return os;
    }
};

And StringEntity

class StringEntity : public Entity {
  public:
    std::string data;

    StringEntity(std::string str) {
        data = str;
    }

    std::ostream& write(std::ostream& os) const {
        os << data;
        return os;
    }
};

Using these classes like so

int main(int argc, char** argv) {
    StringEntity entity = StringEntity("MY STRING ENTITY");
    Entity gen_ent      = (Entity) entity;

    entity.write(std::cout)  << std::endl;
    gen_ent.write(std::cout) << std::endl;
    return 0;
}

Because the base Entity class' write function is virtual and write is overriden in the derived StringEntity class, I would expect both write statements to print out MY STRING ENTITY. Instead, the first one correctly prints MY STRING ENTITY, but the second prints Can't output Entity.

How do I override a function such that it is completely overriden (ie. not dependent upon how a variable is declared)?

functorial
  • 330
  • 3
  • 13

0 Answers0