views:

130

answers:

2

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;
}
+12  A: 

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.

xtofl
+1 Faster than me mate :)
AraK
yep, but A::rofl() is not virtual. Thats the idea - rofl() allways calls virtual rofl(0).
0xDEAD BEEF
@0xDEAD BEEF: in that case, you _intend_ to use it, so make that clear to the compiler by saying `using A::rofl;`.
xtofl
@0xDEAD BEEF: btw, you are creating a 'non-virtual interface' this way; you probably want your `A::rofl(int)` to be pure virtual, and protected.
xtofl
No. I want to crate pure virtual Read(buffer, size, timeout), and wrapper (override) Read(buffer, size) { Read(buffer, size, 0);}BTW - using keyword works great!
0xDEAD BEEF
`@xtofl` with such method names, the question was cut out for you :p
Matthieu M.
+1  A: 

It looks like you're using rofl(int) as a template method.

I suggest making A's rofl(int) protected, and changing the name slightly to avoid clashes.

Alternatively, change A's rofl(int) to have a default value of 0 for x.

MadKeithV