Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Basic C++ inheritance challenged by my compiler?

Tags:

c++

gcc

#include <iostream>

class Base
{
public:
    virtual void ok( float k ){ std::cout<< "ok..." << k; }
    virtual float ok(){ std::cout<< "ok..."; return 42.0f; }
};

class Test : public Base
{
public:
    void ok( float k ) { std::cout<< "OK! " << k; }
    //float ok() { std::cout << "OK!"; return 42; }
};

int main()
{
    Test test;
    float k= test.ok(); 
    return 0;
}

Compilation under GCC 4.4 :

hello_world.cpp: In function `int main()`:
hello_world.cpp:28: erreur: no matching function for call to `Test::ok()`
hello_world.cpp:19: note: candidats sont: virtual void Test::ok(float)

I don't understand why float ok() defined in Base isn't accessible to Test user even if it does publicly inherit from it. I've tried using a pointer to the base class and it does compile. Uncommenting the Test implementation of float ok() works too.

Is it a bug compiler? I'm suspecting a problem related to name masking but I'm not sure at all.

like image 768
Klaim Avatar asked Jul 12 '11 11:07

Klaim


1 Answers

It's called name hiding, any derived class field hides all overloaded fields of the same name in all base classes. To make the method available in Test, add a using directive, i.e.

using Base::ok;

somewhere in the scope of Test. See this for more information.

like image 123
Alexander Gessler Avatar answered Oct 12 '22 13:10

Alexander Gessler