Is redefining and overriding of a function the same thing?

Since both of their purpose is to hide the base class function implementation
Last edited on
The word "overriding" has a very specific meaning.

If someone said "redefining" I would need to look at the context to know what they mean. Normally you're not allowed to define the same thing twice so that is probably not what they mean.
Last edited on

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
// Example program
#include <iostream>
#include <string>

using namespace std;
class base
{ 
public:
     void print()
    {
        cout << "base print " << endl;
    }
    
    
    
};

class derived : public base
{
public:
    void print()
    {
        cout << "derived print " << endl;
    }
    
};



int main()
{
   derived d;
   base* b = &d;
   d.print();
   b->print();
}


I redefined the print function by supplying a new definition at the dervied class. But is it consider overriding?


edit:
Do i have to make it virtual for the function to be consider overriding?
Last edited on
No, this is not overriding.

The derived object still contains a base::print() function that can be invoked, the way you did using a pointer to the base class, or by putting base:: in front of the function name.

1
2
derived d;
d.base::print();
Last edited on
Do i have to make it virtual for the function to be consider overriding?

Yes. You need to mark it virtual in the base class.

You can mark it as virtual in the derived class too if you want but that is not necessary. It will become virtual automatically since it's virtual in the base class. What you might want to do instead is to mark it with override to make sure you're not making a mistake when overriding (e.g. misspelling the function name or getting the parameters wrong).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class base
{ 
public:
    virtual void print()
    {
        cout << "base print " << endl;
    }
};

class derived : public base
{
public:
    void print() override
    {
        cout << "derived print " << endl;
    }
    
};
Last edited on
So if i do not make the function a virtual function then i am just redefining it without overriding it? Am i right to say that?
See my previous answer in case you missed it.

Personally I'm not keen on the word "redefining" to describe this. They are two separate functions so you're not really redefining anything. Instead I might say that derived::print() hides base::print(), which is normally a bad thing.
Last edited on
> So if i do not make the function a virtual function then i am just redefining it without overriding it?

You are hiding the base class function.

When unqualified name lookup examines the scope of the derived class, it finds the declaration of the name in the derived class (and therefore does not examine the base class).
Topic archived. No new replies allowed.