1

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?

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
stustd
  • 303
  • 1
  • 10

1 Answers1

3

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)
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • Wow, that's tricky ...; wouldn't have figured that one out myself. Thanks! Some follow-up questions: - the "hiding", is that b/c virtual methods are resolved at runtime? - is this a common idiom, or is it better /adviced to avoid mixing virtual and non-virtual of member functions with the same name? – stustd Dec 22 '21 at 10:03
  • @stustd Hiding occurs statically. Any name in inner scope hides the same name in the outer scope. – Vlad from Moscow Dec 22 '21 at 10:18