Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Question regarding polymorphiic functions in C++

I am new to C++ and currently I am studying polymorphism.

I have this code:

#include <iostream>
class Base
{
    public:
        void say_hello()
        {
            std::cout << "I am the base object" << std::endl;
        }
};


class Derived: public Base
{
    public:
        void say_hello()
        {
            std::cout << "I am the Derived object" << std::endl;
        }
};

void greetings(Base& obj)
{
    std::cout << "Hi there"<< std::endl;
    obj.say_hello();
}



int main(int argCount, char *args[])
{

    Base b;
    b.say_hello();

    Derived d;
    d.say_hello();

    greetings(b);

    greetings(d);

    return 0;
}

Where the output is:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I am the base object
I am the Derived object
Hi there
I am the base object
Hi there
I am the base object

This is not recognizing the polymorphic nature in the greetings functions.

If I put the virtual keyword in the say_hello() function, this appears to work as expected and outputs:

I am the base object
I am the Derived object
Hi there
I am the base object
Hi there
I am the Derived object

So my question is:
The polymorphic effect is retrieved when using a pointer/reference?

When I see tutorials they will present something like:

Base* ptr = new Derived();
greetings(*ptr);

And I was wondering if had to always resort to pointers when using polymorphism.

Sorry if this question is too basic.

>Solution :

For polymorphic behavior you need 2 things:

  • a virtual method overridden in a derived class
  • an access to a derived object via a base class pointer or reference.
Base* ptr = new Derived();

Those are bad tutorials. Never use owning raw pointers and explicit new/delete. Use smart pointers instead.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading