Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inheritance and method overloading

Tags:

Why C++ compiler gives this error? Why i can access lol() from B, but can not access rofl() [without parameters]. Where is the catch?

class A { public:    void lol(void) {}    void rofl(void) { return rofl(0);}    virtual void rofl(int x) {} };  class B : public A { public:    virtual void rofl(int x) {} };  int _tmain(int argc, _TCHAR* argv[]) {     A a;    a.lol();    a.rofl(1);    a.rofl();     B  b;    b.lol();    b.rofl(1);        b.rofl(); //ERROR -> B::rofl function does not take 0 arguments      return 0; } 
like image 540
0xDEAD BEEF Avatar asked Jun 04 '10 12:06

0xDEAD BEEF


People also ask

What is the difference between overloading and inheritance?

Overloading allows several function definitions for the same name, distinguished primarily through different argument types; it is typically resolved at compile-time. Inheritance allows subclasses to define more special versions of the same function; it is typically resolved at run-time.

Is overloading possible after inheritance?

Yes of course, overloading in inheritance class is possible in Java. Java compiler detect that add method has multiple implementations. so according to the parameter java compiler will determines which method has to be executed. class Parent { public void add(int a) { System.

What is the difference between inheritance and overriding methods?

Inheritance enable us to define a class that takes all the functionality from parent class and allows us to add more. Method overriding occurs simply defining in the child class a method with the same name of a method in the parent class .


1 Answers

The B::rofl(int) 'hides' the A::rofl(). In order to have A's rofl overloads, you should declare B to be using A::rofl;.

class B : public A { public:      using A::rofl;     ... }; 

This is a wise move of C++: it warns you that you probably also need to override the A::rofl() method in B. Either you do that, or you explicitly declare that you use A's other overloads.

like image 169
xtofl Avatar answered Oct 23 '22 00:10

xtofl