CPP in Practice - Developer's Blog
28/02/2021
đź’¬
âś…The reference qualifiers can have only class member functions. Also, called by ref-qualifiers. Ref-qualifiers are new in C++11 and not yet supported in all compilers. They are less-publicized features and maybe you have never heard about them. Reference qualifiers are using to specify that the mentioned function can be called only for lvalue (&) or rvalue (&&) objects.
class Base
{
public:
static Base create() {
return Base();
}
void f() & { … }
void g() && { … }
void h() & { … } /// for lvalue objects
void h() && { … } /// for rvalue objects
};
int main() {
...
Base b;
b.f(); /// OK
b.g(); /// Compile error
…
b.h(); /// OK
Base::create().h(); /// Compile error
}
✅So, we will get compile error if we call g() && and h() && functions carelessly. This is simple case. But, what if f() and g() are virtual? In general, nothing dangerous. But… There are still but. We can mark it as override also in derived class, right? We will speak about override keyword and function signature later, but for now, let’s declare Base and Derived classes:
class Base
{
…
virtual void foo() & { … }
virtual void bar() && { … }
};
class Derived : public base
{
…
virtual void foo() & override { … } /// It’s OK to add “virtual”, but not necessary
virtual void bar() & { … }
};
✅Will Derived::bar() override Base::bar() ?? NO! In virtual table will be created second function pointer named bar. This is because ref-qualifiers also part of function’s signature. This is also good example why we need to write override keyword if we are overriding functions.
📌BTW, about static member functions also can’t have ref-qualifiers.
📚Read more about non-static member functions - https://en.cppreference.com/w/cpp/language/member_functions
📚Read more about lvalue/rvalue references - https://en.cppreference.com/w/cpp/language/reference
Click here to claim your Sponsored Listing.
Category
Website
Address
Yerevan