I have three different base classes:
class BaseA
{
public:
virtual int foo() = 0;
};
class BaseB
{
public:
virtual int foo() { return 42; }
};
class BaseC
{
public:
int foo() { return 42; }
};
I then derive from the base like this (substitute X for A, B or C):
class Child : public BaseX
{
public:
int foo() { return 42; }
};
How is the function overridden in the three different base classes? Are my three following assumptions correct? Are there any other caveats?
c is compiled without override.
Master C and Embedded C Programming- Learn as you go Basically function overriding means redefine a function which is present in the base class, also be defined in the derived class. So the function signatures are the same but the behavior will be different.
Inheritance: Overriding of functions occurs when one class is inherited from another class. Overloading can occur without inheritance. Function Signature: Overloaded functions must differ in function signature ie either number of parameters or type of parameters should differ.
Function overloading is used when we want multiple functions providing similar implementation. However, function overriding is used when we want to add some additional functionality on top of base class implementation.
The important rule to remember is once a function is declared virtual, functions with matching signatures in the derived classes are always virtual. So, it is overridden for Child of A and Child of B, which would behave identically (with the exception of you can't directly instantiate BaseA).
With C, however, the function isn't overridden, but overloaded. In that situation, only the static type matters: it will call it on what it is a pointer to (the static type) instead of what the object really is (the dynamic type)
In the derived class a method is virtual if it is defined virtual in the base class, even if the keyword virtual is not used in the derived class's method.
BaseA
, it will compile and execute as intended, with foo()
being virtual and executing in class Child
.BaseB
, it will also compile and execute as intended, with foo()
being virtual() and executing in class Child
.BaseC
however, it will compile and execute, but it will execute the BaseC
version if you call it from the context of BaseC
, and the Child
version if you call with the context of Child
.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