Search code examples
c++visual-c++

Why can I not access a public function of a base class with a pointer of a subClass?


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.
}

Solution

  • 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);
    }