Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scoping rules when inheriting - C++

Tags:

c++

scope

I was reading the C++0x FAQ by Stroustrup and got stuck with this code. Consider the following code

struct A
{
    void f(double)
    {
        std::cout << "in double" << std::endl;
    }
};

struct B : A
{
    void f(int)
    {
        std::cout << "in int" << std::endl;
    }
};


int main()
{
    A a; a.f(10.10);  // as expected, A.f will get called
    B b; b.f(10.10);  // This calls b.f and we lose the .10 here
    return 0;
}

My understanding was when a type is inherited, all protected and public members will be accessible from the derived class. But according to this example, it looks like I am wrong. I was expecting the b.f will call base classes f. I got the expected result by changing the derived class like

struct B : A
{
    using A::f;
    void f(int)
    {
        std::cout << "in int" << std::endl;
    }
};

Questions

  1. Why was it not working in the first code?
  2. Which section in the C++ standard describes all these scoping rules?
like image 357
Navaneeth K N Avatar asked Jun 17 '09 08:06

Navaneeth K N


3 Answers

Its because A::f is "hidden" rather than "overloaded" or "overridden". Refer:

http://www.parashift.com/c++-faq-lite/strange-inheritance.html#faq-23.9

like image 83
aJ. Avatar answered Oct 03 '22 13:10

aJ.


The first code works as c++ is designed to work.

Overloading resolution follows a very complicated set of rules. From Stroustrup's c++ bible 15.2.2 "[A]mbiguities between functions from different base classes are not resolved based on argument types."

He goes on to explain the use of "using" as you have described.

This was a design decision in the language.

I tend to follow the Stroustrup book rather than the standard, but I'm sure it is in there.

[Edit]

Here it is (from the standard):

Chapter 13

When two or more different declarations are specified for a single name in the same scope, that name is said to be overloaded.

And then:

13.2 Declaration matching

1 Two function declarations of the same name refer to the same function if they are in the same scope and have equivalent parameter declarations (13.1). A function member of a derived class is not in the same scope as a function member of the same name in a base class.

like image 27
morechilli Avatar answered Oct 03 '22 13:10

morechilli


Search for overload resolution. A similar, but not identical question.

like image 40
Pontus Gagge Avatar answered Oct 03 '22 13:10

Pontus Gagge