-2

I'd like to be able to group similar functions in a class into a group so I don't need to append each name with what it's about.

I've seen this question which says that you can't have namespaces within classes. I've also seen this question which proposes using strongly typed enums. The problem here though, is that I'm not sure whether or not these enums can actually accomodate functions?

The problem contextualised:

class Semaphore
{
public:

    void Set(bool State){Semaphore = State;}
    bool Get(){return Semaphore;}
    void Wait()
    {
        while (Semaphore)
        {
            //Wait until the node becomes available.
        }
        return;
    }
private:
    bool Semaphore      = 0;            //Don't operate on the same target simultaneously.
};

class Node : Semaphore
{
public:
    unsigned long IP    = 0;            //IP should be stored in network order.
    bool IsNeighbour    = 0;            //Single hop.

    std::vector<int> OpenPorts;
    //Rest of code...
};

Currently, NodeClass.Get() is how I can get the semaphore. However this introduces confusion as to what Get() actually gets. I'd like to have something akin to NodeClass.Semaphore::Get(). Otherwise I'd have to have the functions as SemaphoreSet(), SemaphoreGet(), and SemaphoreWait(), which isn't too well organised or nice looking.

I had thought of just having the Semaphore class on it's own, and instantiating it within the other classes, but if I could stick with the inheritance approach, that would be nicer.

So essentially, is it possible to access inherited methods like InheritedClass.Group::Function()?

1 Answers1

1

If you really want to do this, you could force the user to call with the base class name by deleteing the member function in the subclass:

class Base {
  public:
    void Set(bool) { }
};

class Derived : public Base {
  public:
    void Set(bool) = delete;
};

int main() {
    Derived d;
    // d.Set(true); // compiler error
    d.Base::Set(true);
}

However, if the semantics of calling Set on the subclass are significantly different than what you'd expect them to be when calling Set on the base class, you should probably use a data member and name a member function accordingly as you've described:

class Base {
  public:
    void Set(bool) { }
};

class Derived {
  public:
    void SetBase(bool b) {
        b_.Set(b);
    }
  private:
    Base b_;
};

int main() {
    Derived d;
    d.SetBase(true);
}
Ryan Haining
  • 35,360
  • 15
  • 114
  • 174