I wish to understand why a pointer to the "Derived" class object has to be used as an argument of the "PrintName" function in order to override the virtual "GetName" function. Why can a stack-allocated class object not be passed instead?
Why can't I do this:
class Base
{
public:
virtual std::string GetName()
{
return "Base";
}
};
class Derived: public Base
{
public:
std::string GetName() override
{
return "Derived";
}
};
void PrintName(Base obj)
{
std::cout << obj.GetName() << std::endl;
}
int main()
{
Base b;
PrintName(b);
Derived d ;
PrintName(d);
std::cin.get();
return 0;
}
But have to do this:
...
void PrintName(Base* obj)
{
std::cout << obj->GetName() << std::endl;
}
int main()
{
Base* b = new Base();
PrintName(b);
Derived* d = new Derived();
PrintName(d);
std::cin.get();
return 0;
}