1

I cannot access the non-virtual Base::f() via Child while Base::g() is accessible. Demo also on cpp.sh: http://cpp.sh/54ne7

I am more interested in the theoretical background then getting solutions (as CASE 3, CASE 4 and CASE 5 are already workarounds).

#include <iostream>
#include <vector>

struct Base 
{
    void f( const std::vector<int> &v )
    {
        f( v.data( ), v.size( ) );
    }
    void g( const std::vector<int> &v )
    {
        f( v.data( ), v.size( ) );
    }
    virtual void f( const int *data, ssize_t length )
    {
        for ( auto i = 0u; i < length; i++ )
        {
            std::cout << data[ i ] << " ";
        }
        std::cout << std::endl;
    }
};

struct Child : public Base
{
    void f( const int *data, ssize_t length ) override
    {
      for ( auto i = 0u; i < length; i++ ) 
      {
          std::cout << std::hex << data[ i ] << " ";
      }
      std::cout << std::endl;
    }
};

int main()
{
    std::vector<int> v = { 10, 10, 10, 10, 10 };
    /*-- CASE 1: OK --*/
    Base b1;
    b1.f( v );

    /*-- CASE 2: won't compile --*/
    // Child c2;
    // c2.f( v ); 

    /*-- CASE 3: OK --*/
    Child c3;
    c3.g( v ); 

    /*-- CASE 4: OK --*/
    Child c4;
    c4.Base::f( v ); 

    /*-- CASE 5: OK --*/
    Base *c5 = new Child( );
    c5->f( v );
}
  • Function `f` in `Child` shadows overloads available in `Base`. You can bring them back in with `using Base::f;` in `Child` class scope. – Yksisarvinen Jul 06 '21 at 14:10

0 Answers0