Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ inheritance - same method name with different argument type

I'm trying to compile following code in VC++ 2010:

class Base
{
public:
    std::wstring GetString(unsigned id) const
    {
        return L"base";
    }
};

class Derived : public Base
{
public:
    std::wstring GetString(const std::wstring& id) const
    {
        return L"derived";
    }
};

int wmain(int argc, wchar_t* argv[])
{
    Derived d;

    d.GetString(1);
}

My understanding was that Derived will have two methods:

std::wstring GetString(unsigned id) const
std::wstring GetString(const std::wstring& id) const

so my code should compile succesfully. Visual C++ 2010 however reports following error:

test.cpp(32): error C2664: 'Derived::GetString' : cannot convert parameter 1 from 'int' to 'const std::wstring &'
      Reason: cannot convert from 'int' to 'const std::wstring'
      No constructor could take the source type, or constructor overload resolution was ambiguous

What am I doing wrong? The code works perfectly when I use it this way:

Derived d;
Base base = d;
base.GetString(1);

or when both variants of GetString are defined in same class.

Any ideas? I would like to avoid explicit typecasting.

like image 991
imagi Avatar asked Dec 17 '22 06:12

imagi


1 Answers

Derived::GetString hides Base::GetString.* To solve this, do the following:

class Derived : public Base
{
public:
    using Base::GetString;

    std::wstring GetString(const std::wstring& id) const
    {
        return L"derived";
    }
};


* For fairly obscure reasons that Scott Meyers explains in Chapter 50 of "Effective C++".

See also http://www.parashift.com/c++-faq-lite/strange-inheritance.html#faq-23.9.

like image 101
Oliver Charlesworth Avatar answered Mar 15 '23 22:03

Oliver Charlesworth