简体   繁体   中英

Inheritance or Polymorphism?

I did a programmer's test few weeks ago and did not pass. The test was those full of "gotch you!" c++ questions, that had nothing to do with what we face on a day to day coding. I wish I had printed out all of them and posted online, but too late. One I remember and I wonder if someone can clarify with certainty the best answer.

Does the code below show an example of inheritance or polymorphism? To me, is both, but I ended up answering inheritance since it only gave me on option to pick. The derived class is clearly inheriting properties from the base class, but since there is only a change in behavior of a method, it can also be a polymorphism example.

any comments?

class Base
{
public:
    Base() {}
    ~Base() {}

    virtual int Foo(int a)
    {
        return a*a;
    }

};

class Derived : public Base
{
public:
    Derived() {}
    ~Derived() {}

    int Foo(int a)
    {
        return a*a*a;
    }
};

Well it's clearly showing inheritance. It's hard to have polymorphism without inheritance though (although you can do compile-time polymorphism with templates). I don't think this code is showing polymorphism - that has to involve using a derived object through a base pointer / reference.

So:

    Derived d;
    d.Foo(5);   // No polymorphism.

But

    std::unique_ptr<Base>() Factory(int i);
    auto pBase = Factory(1);
    auto a = pBase->Foo(5);  // *This* is polymorphism

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM