Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

visual-c++

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.
}
like image 423
Aaron Fischer Avatar asked Nov 18 '25 21:11

Aaron Fischer


2 Answers

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);
}
like image 123
Greg Bacon Avatar answered Nov 20 '25 11:11

Greg Bacon


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.

like image 33
quamrana Avatar answered Nov 20 '25 10:11

quamrana



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!