0

Using the using-directive I'm able to select a certain set of methods from the base class to put into a different access scope. Is this also possible for individual overloads of the method? Something like this:

Demo

#include <iostream>

class base {

public:
    auto print() -> void {
        std::cout << "Hello World" << std::endl;
    }
    auto something_else(int) -> void {
        std::cout << "Hello int stuff" << std::endl;
    }
    auto something_else(bool) -> void {
        std::cout << "Hello bool stuff" << std::endl;
    }

};

class derived : public base {
public:
    using base::something_else(bool);
private:
    using base::something_else(int);
};

int main() {
    derived d;

    d.print();
    d.something_else(2);
    d.something_else(true);
}
glades
  • 3,778
  • 1
  • 12
  • 34
  • 1
    Individual ones – no. Apart from it is not a good idea to reduce accessibility of a base class function in a derived one, violates the *'is a'* relationship like *'why should animals eat but mice not?'* – Aconcagua Jun 29 '23 at 08:21
  • @Aconcagua bc I'm lazy and I don't want to redefine the whole interface my derived that only slightly modificates the base class functionality ;) – glades Jun 29 '23 at 08:27
  • @glades This is being lazy in the wrong way. Coding is about being explicit what you mean not about finding tricks to type less. And using inheritance for code reuse is going to bite back later. So put the reusable code somewhere else and aggregate it or call it. – Pepijn Kramer Jun 29 '23 at 08:29
  • @PepijnKramer I'm deriving from std::vector for a "domain" class that can hold an arbitrarily long domain name but you can access each part by operator[]. Naturally, if the user assigns to this class it should parse the domain and split by seperating dots '.', so the assignement of vector otherwise should not be possible. – glades Jun 29 '23 at 08:32
  • 2
    Deriving from stl classes is also not recommended (vector doesn't have a virtual destructor which in my book is a clear hint). Just use aggregation. Make your std::vector a member and expose forwarding methods on your own class. – Pepijn Kramer Jun 29 '23 at 08:37
  • The main critical point in this concrete scenario: You cannot prevent calling the base class functions (in your case: suppress assignment) anyway – what if the derived is bound to reference of base? Then all what you try to hide away is available again… – Aconcagua Jun 29 '23 at 08:45
  • 1
    So just take a little pain now (writing some extra lines of code) to avoid a lot of pain later. :) – Pepijn Kramer Jun 29 '23 at 08:49

0 Answers0