Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ polymorphism and virtual function

Is it possible to call the virtual function foo( int ) from B without using what is done in comment ?

class A {
public: 

    virtual void foo ( char * ) {
    }

    virtual void foo ( int ) {
    }
};

class B : public A {
public:

    void foo ( char * ) {
    }

    //void foo ( int i ) {
    //  
    //  A::foo(i);
    //}
};

B b;
b.foo(123); // cannot convert argument 1 from 'int' to 'char *'
like image 957
Franck Freiburger Avatar asked Sep 11 '14 17:09

Franck Freiburger


People also ask

Is polymorphism the same as virtual functions?

A virtual function is a special type of function that, when called, resolves to the most-derived version of the function that exists between the base and derived class. This capability is known as polymorphism.

Is virtual function used in polymorphism?

The main use of virtual function is to achieve Runtime Polymorphism. Runtime polymorphism can be achieved only through a pointer (or reference) of base class type.

What is virtual function & polymorphism C++?

A virtual function in C++ is a base class member function that you can redefine in a derived class to achieve polymorphism. You can declare the function in the base class using the virtual keyword.

How virtual function is related to runtime polymorphism?

Virtual Functions and Runtime Polymorphism in C++It tells the compiler to perform late binding where the compiler matches the object with the right called function and executes it during the runtime. This technique of falls under Runtime Polymorphism. The term Polymorphism means the ability to take many forms.


1 Answers

Yes, it is possible. The problem here is that the function B::foo(char*) hides the name of the inherited function A::foo(int), but you can bring it back into scope of B with a using declaration:

class B : public A {
public:

    void foo ( char * ) {
    }

    using A::foo;
};
like image 60
Angew is no longer proud of SO Avatar answered Nov 09 '22 10:11

Angew is no longer proud of SO