dimanche 28 novembre 2021

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:

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.

Aucun commentaire:

Enregistrer un commentaire