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.
CodePudding user response:
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.
CodePudding user response:
Just add a virtual declaration to the method to allow it to be overridden when using references to the base class:
virtual void say_hello() {...}
in both classes (or at least just the base class).