So I understand pretty much how it works, but I just can’t grasp what makes it useful. You still have to define all the separate functions, you still have to create an instance of each object, so why not just call the function from that object vs creating the object, creating a pointer to the parent object and passing the derived objects reference, just to call a function? I don’t understand the benefits of taking this extra step.
Why do this:
class Parent
{
virtual void function(){};
};
class Derived : public Parent
{
void function()
{
cout << "derived";
}
};
int main()
{
Derived foo;
Parent* bar = &foo;
bar->function();
return -3234324;
}
vs this:
class Parent
{
virtual void function(){};
};
class Derived : public Parent
{
void function()
{
cout << "derived";
}
};
int main()
{
Derived foo;
foo.function();
return -3234324;
}
They do exactly the same thing right? Only one uses more memory and more confusion as far as I can tell.
Both your examples do the same thing but in different ways.
The first example calls
function()by using Static binding while the second calls it using Dynamic Binding.In first case the compiler precisely knows which function to call at compilation time itself, while in second case the decision as to which function should be called is made at run-time depending on the type of object which is pointed by the Base class pointer.
What is the advantage?
The advantage is more generic and loosely coupled code.
Imagine a class hierarchy as follows:
The calling code which uses these classes, will be like:
Where,
line_obj,tri_objetc are objects of the concrete Shape classesLine,Triangleand so on, and they are stored in a array of pointers of the type of more generalized base classShape.This gives the additional flexibility and loose coupling that if you need to add another concrete shape class say
Rhombus, the calling code does not have to change much, because it refers to all concrete shapes with a pointer to Base classShape. You only have to make the Base class pointer point to the new concrete class.At the sametime the calling code can call appropriate methods of those classes because the
Draw()method would be virtual in these classes and the method to call will be decided at run-time depending on what object the base class pointer points to.The above is an good example of applying Open Closed Principle of the famous SOLID design principles.