Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using declaration in class definition

Tags:

c++

c++11

I found that 'using' keyword can be used in class definition. according to https://en.cppreference.com/w/cpp/language/using_declaration, its used for member function is as follows:

If the name is the name of an overloaded member function of the base class, all base class member functions with that name are introduced. If the derived class already has a member with the same name, parameter list, and qualifications, the derived class member hides or overrides (doesn't conflict with) the member that is introduced from the base class.

an example code is as follows:

#include <iostream>
struct B {
    virtual void f(int) { std::cout << "B::f\n"; }
    void g(char)        { std::cout << "B::g\n"; }
    void h(int)         { std::cout << "B::h\n"; }
 protected:
    int m; // B::m is protected
    typedef int value_type;
};

struct D : B {
    using B::m; // D::m is public
    using B::value_type; // D::value_type is public

    using B::f;
    void f(int) { std::cout << "D::f\n"; } // D::f(int) overrides     B::f(int)
    using B::g;
    void g(int) { std::cout << "D::g\n"; } // both g(int) and g(char) are visible
                                       // as members of D
    using B::h;
    void h(int) { std::cout << "D::h\n"; } // D::h(int) hides B::h(int)
};

int main()
{
    D d;
    B& b = d;

//    b.m = 2; // error, B::m is protected
    d.m = 1; // protected B::m is accessible as public D::m
    b.f(1); // calls derived f()
    d.f(1); // calls derived f()
    d.g(1); // calls derived g(int)
    d.g('a'); // calls base g(char)
    b.h(1); // calls base h()
    d.h(1); // calls derived h()
}

From the above code, I am not sure what is the difference, for instance

using B::f;
void f(int)

and

virtual void f(int)

Is there definite difference for using 'using' keyword in order to override class member function?

like image 311
Seong Avatar asked Aug 27 '26 12:08

Seong


1 Answers

The wording from that article is unfortunate. They tried to fix it with the parenthetical, but…

This has nothing to do with virtual function overriding.

The two examples you give are different and unrelated.

One brings the base class f into scope, then chucks that away and introduces a new D::f function. (This will not be virtual unless B::f already was, per the normal rules).

The other declares a virtual D::f.

like image 181
Lightness Races in Orbit Avatar answered Aug 29 '26 11:08

Lightness Races in Orbit



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!