C ++ Inheritance is the same method name with a different type of argument

I am trying to compile the 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); } 

I realized that Derived will have two methods:

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

so my code must compile successfully. Visual C ++ 2010 reports the 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 fine when I use it like this:

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

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

Any ideas? I would like to avoid explicit typecasting.

+4
source share
1 answer

Derived::GetString hides Base::GetString . * To solve this problem, follow these steps:

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


* For rather obscure reasons that Scott Myers explains in Chapter 50, Effective C ++.

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

+10
source

Source: https://habr.com/ru/post/1386410/


All Articles