runtime binding inheritence

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
class Base {
  public:
  virtual int f() const {
cout << "Base::f()\n";
       return 1;
}
 virtual void f(string) const {}
 virtual void g() const {}
};

class Derived4 : public Base {
  public:
       int f(int) const {
         cout << "Derived4::f()\n";
         return 4;
    }
};

int main()
{
	string s("hello");

	Derived4 d4;
	Base& br = d4; // Upcast
	// br.f(1); // Derived version unavailable
	br.f(); // why does it compile ?
	br.f(s);// why does it compile ?
}


In derived : overloading f() of base .. so all base f() versions hidden .
Now , because of runtime binding , f() and f(s) of derived should be called , BUT they are hidden.



Q : What am i missing?
Q : br.f(1); does not compile because , during compile time , int f(int) is not present in Base . Am i correct?
Last edited on
There are three different functions named f:
- f() - virtual but never overridden
- f(string) - virtual but never overridden
- f(int) - not virtual, introduced by the derived class

Even if you properly override a virtual function, it is still possible to access it:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
struct Base
{
    virtual void f(){ std::cout << "Base::f()" << std::endl; }
};
struct Derived
: Base
{
    virtual void f() override { std::cout << "Derived::f()" << std::endl; }
};

//...

Derived d;
Base &b = d;

d.f(); //calls Derived::f()
b.f(); //calls Derived::f()
d.Base::f(); //calls Base::f()
b.Base::f(); //calls Base::f() 
http://ideone.com/ssGca7
Last edited on
@LB,
I understood your answer , but in my question, i have not used br.Base::f() , but simply used Br.f() and it still compiles. Why?
int f(int) has overloaded int f() , so all base class f() should not be visible to Derived.
Because of late binding, Derived::f() should be called , not Base::f().
But this is not what the code agrees with.
No, f() does not override f(int) because they are two completely different signatures. A function's name is only one part of what makes a function unique. The argument types and const/volatile/&/&& also factor into a function's signature.

EDIT: This should clear things up:
http://ideone.com/iZVtww
Last edited on
Topic archived. No new replies allowed.