Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why should I use the "using" keyword to access my base class method?

I wrote the below code in order to explain my issue. If I comment the line 11 (with the keyword "using"), the compiler does not compile the file and displays this error: invalid conversion from 'char' to 'const char*'. It seems to not see the method void action(char) of the Parent class in the Son class.

Why the compiler behave this way? Or have I done something wrong?

class Parent {     public:         virtual void action( const char how ){ this->action( &how ); }         virtual void action( const char * how ) = 0; };  class Son : public Parent {     public:         using Parent::action; // Why should i write this line?         void action( const char * how ){ printf( "Action: %c\n", *how ); } };  int main( int argc, char** argv ) {     Son s = Son();     s.action( 'a' );     return 0; } 
like image 264
Julien Vaslet Avatar asked Dec 13 '09 15:12

Julien Vaslet


People also ask

What should be used to call the base class method?

base (C# Reference) The base keyword is used to access members of the base class from within a derived class: Call a method on the base class that has been overridden by another method.

Which keyword is used for the member function of the base class?

Explanation: The keyword super must be used to access base class members.

Which Java keyword do you use to call a method from the base class?

The super keyword in Java acts like a reference variable to the parent class. It's mainly used when we want to access a variable, method, or constructor in the base class, from the derived class. Let's have a look at some examples to understand how exactly the super keyword works.

How can we access the base class implementation?

To access the overridden function of the base class, we use the scope resolution operator :: . We can also access the overridden function by using a pointer of the base class to point to an object of the derived class and then calling the function from that pointer.


1 Answers

The action declared in the derived class hides the action declared in the base class. If you use action on a Son object the compiler will search in the methods declared in Son, find one called action, and use that. It won't go on to search in the base class's methods, since it already found a matching name.

Then that method doesn't match the parameters of the call and you get an error.

See also the C++ FAQ for more explanations on this topic.

like image 200
sth Avatar answered Oct 05 '22 09:10

sth