If the base class has both const and non-const version of a function, can I refer to only one or the other in the derived class by the using keyword?
struct Base
{
protected:
int x = 1;
const int& getX() const {return x;}
int& getX() {return x;}
};
struct Derived : public Base
{
public:
using Base::getX; // Can we refer to the const or the non-const only?
};
If no, whats the simplest way to make const getX()
public in Derived without repeating the function body?
Using-declarations can be used to introduce namespace members into other namespaces and block scopes, or to introduce base class members into derived class definitions, or to introduce enumerators into namespaces, block, and class scopes (since C++20).
A using declaration in a definition of a class A allows you to introduce a name of a data member or member function from a base class of A into the scope of A .
Overloading on the basis of const type can be useful when a function return reference or pointer. We can make one function const, that returns a const reference or const pointer, other non-const function, that returns non-const reference or pointer. See this for more details.
C++ allows member methods to be overloaded on the basis of const type. Overloading on the basis of const type can be useful when a function return reference or pointer.
The const declaration creates a read-only reference to a value. It does not mean the value it holds is immutable—just that the variable identifier cannot be reassigned. For instance, in the case where the content is an object, this means the object's contents (e.g., its properties) can be altered.
C++ allows functions to be overloaded on the basis of const-ness of parameters only if the const parameter is a reference or a pointer. That is why the program 1 failed in compilation, but the program 2 worked fine. This rule actually makes sense. In program 1, the parameter ‘i’ is passed by value, so ‘i’ in fun () is a copy of ‘i’ in main ().
using
always brings the entire overload set for the given name with it. You cannot invoke using
for a particular function, only for its name, which includes all uses of that name.
You will have to write a derived-class version of the function, with your preferred signature, that calls the base class. The simplest way would be with decltype(auto) getX() const { return Base::getX(); }
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With