Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

virtual function overriding in C++

Tags:

c++

c#

oop

I have a base class with virtual function - int Start(bool) In the derived there is a function with the same name but with a different signature -

int Start(bool, MyType *)

But Not virtual

In the derived Start(), I want to call the base class Start()

int Derived::Start(bool b, MyType *mType)
{
    m_mType = mType;
    return Start(b);
}

But it gives compilation error.

"Start' : function does not take 1 arguments"

However Base::Start(b) works

In C#, the above code works i.e the reference to Base is not required for resolving the call.

Externally if the call is made as follows

Derived *d = new Derived();
bool b;
d->Start(b);

It fails with the message:

Start : function does not take 1 arguments

But in C#, the same scenaio works.

As I understand the virtual mechanism cannot be used for resolving the call, because the two functions have different signature.

But the calls are not getting resolved as expected.

Please help

like image 269
G.S Avatar asked May 12 '26 23:05

G.S


2 Answers

Your two options are either add using Base::Start to resolve the scope of Start

int Derived::Start(bool b, MyType *mType)
{
    using Base::Start;
    m_mType = mType;
    return Start(b);
}

Or as you noted add the Base:: prefix.

int Derived::Start(bool b, MyType *mType)
{
    m_mType = mType;
    return Base::Start(b);
}
like image 139
Cory Kramer Avatar answered May 14 '26 12:05

Cory Kramer


This is due to name hiding.

When you declare a function in a derived class with the same name as one in the base class, the base class versions are hidden and inaccessible with an unqualified call.

You have two options: either fully qualify your call like Base::Start(b), or put a using declaration in your class:

using Base::Start;
like image 40
TartanLlama Avatar answered May 14 '26 14:05

TartanLlama



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!