Jump to content
  • Advertisement
Sign in to follow this  
RavNaz

What is polymorphism...

This topic is 3452 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I need to describe this in a simple statement.. ish... I can give an example of Polymorphism.. as in class Base { virtual something() {..} }; class Derived : public Base { virtual something() {..} }; Base* a = new Derived; a->something(); // where 'something' called will go through Derived::something() but how do I describe in 1-2lines, so its' easy to understand?

Share this post


Link to post
Share on other sites
Advertisement
That's not an example of polymorphism. That's an example of virtual function binding, which is a C++ feature used to allow polymorphism. If you want to understand and therefore describe polymorphism, I suggest that you think of a better real-world example than "Base", "Derived" and "something".

Share this post


Link to post
Share on other sites
In practical terms, and quoting the Wikipedia, polymorphism is an abstraction that enables one common interface for many implementations, and for objects to act differently under different circumstances.

In C++, you have different types of polymorphism:


  • Dynamic (runtime, inclusion) polymorphism: achieved through the virtual function binding mechanism.


    #include <iostream>

    struct Foo
    {
    virtual void execute() { std::cout << "Foo::execute()" << '\n'; }
    virtual ~Foo() { }
    };

    struct Bar : Foo
    {
    void execute() { std::cout << "Bar::execute()" << '\n'; }
    };

    int main()
    {
    Foo* f = new Bar();
    f->execute(); // prints 'Bar::execute()'
    delete f;
    }


  • Static (compile-time, parametric) polymorphism: achieved through the template mechanism.


    #include <iostream>

    struct Foo
    {
    void execute() const { std::cout << "Foo::execute()" << '\n'; }
    };

    struct Bar
    {
    void execute() const { std::cout << "Bar::execute()" << '\n'; }
    };

    template <typename T>
    void execute(const T& t)
    {
    t.execute();
    }

    int main()
    {
    Foo f;
    Bar b;

    execute(f); // prints 'Foo::execute()'
    execute(b); // prints 'Bar::execute()'
    }


  • Ad-hoc polymorphism: achieved through function overloading and type coercion.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!