Override a private virtual public function?

Consider two classes A, and Bthe following interface:

class A {
public:
    virtual void start() {} //default implementation does nothing
};

class B {
public:
    void start() {/*do some stuff*/}
};

and then the third class, which inherits from both, Apublicly, because it implements this "interface" and Bconfidentially, because this implementation detail.

However, in this particular implementation start()should contain only a call B::start(). So I decided to use a shortcut and do the following:

class C: public A, private B {
public:
    using B::start;
};

and get it over with, but apparently it won’t work. Therefore, I get usinga private base function that does not work to override virtual ones. Hence two questions:

  • Is there any way to make this work, as I suggested that it might have worked?
  • ? , start() C, A::start().

: :

  • , C A.
  • , B::start(), , "" , , .
  • , virtual .
+4
2

, , , , ?

- B::start():

class C: public A, private B {
public:
    void start() override { B::start(); }
};

? , start() C A::start().

, C (A::start() B::start()) -. class C, start() start() , using ...::start(), - namelookup C.

class A {
public:
    virtual void start() { std::cout << "From A\n"; }
};

class B {
public:
    void start() { std::cout << "From B\n"; }
};

class C: public A, private B {
};

int main(){
    A* a = new C();
    a->start();       //Ok, calls A::start()

    C* c = new C();
    c->start();       //Error, ambiguous         
}

, , :

    C* c = new C();
    c->A::start();       //Ok, calls A::start()

using B::start() class C start() B::start(), C

class A {
public:
    virtual void start() { std::cout << "From A\n"; }
};

class B {
public:
    void start() { std::cout << "From B\n"; }
};

class C: public A, private B {
public:
     using B::start();
};

int main(){
    A* a = new C();
    a->start();       //Ok, calls A::start()

    C* c = new C();
    c->start();       //Ok, calls B::start()
}

using B::start void B::start() C, . -, B::start(), - C B::start()

class A {
public:
    virtual void start() { std::cout << "From A\n"; }
};

class B {
public:
    void start() { std::cout << "From B\n"; }
};

class C: public A, private B {
public:
    void start() override { B::start(); }
};

int main(){
    A* a = new C();
    a->start();         //Ok, calls C::start() which in turn calls B::start()
                        //    ^^^^^^^^^^^^^^^^ - by virtual dispatch

    C* c = new C();
    c->start();         //Ok, calls C::start() which in turn calls B::start()

}
+5

, , "public" 'private'. ++ , , "C" "A" , "B" "C" "C" ( "B" ).

. using B::start; ( c.start()), ( A B), 't .

, , c()->start(); "A" "B" , using , . , , - "A" ?

0

Source: https://habr.com/ru/post/1667553/


All Articles