Home > Back-end >  Is modifying a function in derived class and accessing it by derived class object itself an example
Is modifying a function in derived class and accessing it by derived class object itself an example

Time:12-19

I was reading about function overriding and run-time polymorphism online.

While reading I found an example of function overriding on programiz where following example was given :

// C   program to demonstrate function overriding

#include <iostream>
using namespace std;

class Base {
   public:
    void print() {
        cout << "Base Function" << endl;
    }
};

class Derived : public Base {
   public:
    void print() {
        cout << "Derived Function" << endl;
    }
};

int main() {
    Derived derived1;
    derived1.print();
    return 0;
}

Output

Derived Function

Here in Derived class we have modified print() function of Base class and is accessed by an object derived1 of the derived class.

A question stuck in my mind - is this an example of runtime polymorphism also? or operator overriding not always comes under runtime polymorphism as I have read this somewhere

The main use of virtual function is to achieve Runtime Polymorphism.Runtime polymorphism can be achieved only through a pointer (or reference) of base class type.

Hence my question is - "Is this an example of run-time polymorphism as does not use the virtual keyword and involves a pointer to base class and even an example of function overriding?

Correct me if I have mentioned anything wrong.

CodePudding user response:

This is not runtime polymorphism.

The site doesn't claim that either, but it is using the term "override" incorrectly (or at least not with the usual technical meaning). Only virtual functions can be overridden and then the override provides runtime polymorphism.

What the site is demonstrating is simply (compile-time static) name lookup rules of class members. No polymorphism or overriding. C simply allows entities with the same name in different namespaces and classes and has rules on how to decide which of these a given expression names. These entities are not related at all. For example you can have a static data member static int mem; in a base class and a non-static member function void mem(); in a derived class. If you write obj.mem it will either be the static data member (if obj's static type is the base class) or the non-static member function (if obj's static type is the derived class). These obviously have nothing to do with one another.

  • Related