tags:

views:

234

answers:

5

I am not sure why I am getting an "error C2660: 'SubClass::Data' : function does not take 2 arguments". when i try to compile my project.

I have a base class with a function called data. The function takes one argument, There is an overload of Data that takes 2 arguments. In my subClass I override the data function taking 1 argument. Now when I try to call the overload of data from a pointer to subClass I receive the above compile error.

class Base : public CDocument
{
Public:
virtual CString&    Data( UINT index);  
CString  Data( UINT index, int pos); 
};
class SubClass : public Base
{
Public:
virtual CString&    Data( UINT index);  

};

Void SomeOtherFunction()
{
subType* test = new subType();
test->Data( 1, 1);// will not compile
((Base*)test)->Data(1,1); // compiles with fine.
}
+1  A: 

You have to add using Base::Data in your SubClass

Take a look at Item 33: Avoid hiding inherited names of Effective C++

Nikola Smiljanić
+6  A: 

The C++ Programming Language by Bjarne Stroustrup (p. 392, 2nd ed.):

15.2.2 Inheritance and Using-Declarations
Overload resolution is not applied across different class scopes (§7.4) …

You can access it with a qualified name:

void SomeOtherFunction()
{
  SubClass* test = new SubClass();

  test->Base::Data(1, 1);
}

or by adding a using-declaration to SubClass:

class SubClass : public Base
{
  public:
  using Base::Data;
  virtual CString& Data( UINT index);
};

void SomeOtherFunction()
{
  SubClass* test = new SubClass();

  test->Data(1, 1);
}
Greg Bacon
+1  A: 

It's the hiding rule trying to protect you from yourself.

Adrian McCarthy
+2  A: 

Your override of Data(UINT index) in SubClass 'hides' the overload in the base class.

A solution is to code SubClass like this:

class SubClass : public Base
{
public:
using Base::Data;    // <--- brings all the overloads into scope
virtual CString&    Data( UINT index);          
};

Now test->Data(1,1) should work.

quamrana
A: 

When you override the function declared in the base class, all other functions with that name becomes hidden in the subclass. As mentioned previously, you would need to bring those names into the scope of the subclass through the using Base::Data declaration.

jasonline