c++classscopevirtualusing-declaration

Observation (check): same member function name, different signature, one as virtual member


I'm afraid this is not possible:

class A {

public:

    A(){}

    virtual string s() = 0
            string s(int i) {
                auto j = this->s(); 
                ... modify j ...
                return j;
};

class B: public A{

public:

    B() : A() {}

    string s() override {
       return string("Class B"); // just some string
    }
};

In other words: you cannot have two member functions variants only one of which is virtual? Is that observation correct?


Solution

  • You may use virtual and non -virtual functions with the same name in base and derived classes.

    In the example of classes in your question the definition of the virtual function s in the derived class B hides the non-virtual function with the same name declared in the base class A.

    string s() override {
       return string("Class B"); // just some string
    }
    

    To make it visible in the scope of the derived class you can use the using declaration.

    Here is a demonstration program.

    #include <iostream>
    #include <string>
    
    int main()
    {
        struct A
        {
            std::string f( int i ) const 
            {
                return f() + '(' + std::to_string( i ) + ')';
            }
    
            virtual std::string f() const
            {
                return "struct A";
            }
    
            virtual ~A() = default;
        };
    
        struct B : A
        {
            using A::f;
    
            virtual std::string f() const override
            {
                return "struct B";
            }
        };
    
        B b;
    
        std::cout << b.f( 1 ) << '\n';
    
        A &rb = b;
    
        std::cout << rb.f( 2 ) << '\n';
    
        A a;
    
        std::cout << a.f( 3 ) << '\n';
    }
    

    The program output is

    struct B(1)
    struct B(2)
    struct A(3)