According to the docs on inheritance:
Derived classes may override methods of their base classes. Because methods have no special privileges when calling other methods of the same object, a method of a base class that calls another method defined in the same base class may end up calling a method of a derived class that overrides it.
How does that happen? Can someone illustrate this concept with a simple example?
Access Overridden Function in C++ To access the overridden function of the base class, we use the scope resolution operator :: . We can also access the overridden function by using a pointer of the base class to point to an object of the derived class and then calling the function from that pointer.
Invoking overridden method from sub-class : We can call parent class method in overriding method using super keyword. Overriding and constructor : We can not override constructor as parent and child class can never have constructor with same name(Constructor name must always be same as Class name).
The main advantage of method overriding is that the class can give its own specific implementation to a inherited method without even modifying the parent class code.
Here's the example you requested. This prints chocolate
.
class Base: def foo(self): print("foo") def bar(self): self.foo() class Derived(Base): def foo(self): print("chocolate") d = Derived() d.bar() # prints "chocolate"
The string chocolate
is printed instead of foo
because Derived
overrides the foo()
function. Even though bar()
is defined in Base
, it ends up calling the Derived
implementation of foo()
instead of the Base
implementation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With