Can two classes inheriting the same base class use eachother's functions?

I've been stuck on this problem based on inheritance in C++ and I'm unsure if my approach is even correct.

class A
{
private:
   string s;
public: 
   A(string s);
   virtual ~A;
   virtual void set(string s);
   virtual string get();
 };

class B : public virtual A
{
public:
   void set(string s);
   string get();
}

class C : public virtual A
{
public:
   void set(string s);
}

class D : public B, public C
{
public:
   void set(string s);
}

When calling the set method from D my code should call the set method of C but then somehow call the get method of B while inside of the set method of C. I don't understand how that's actually possible since B and C are completely unrelated other than they both inherit the same base class. I'm sure it's an issue with how I've done these headers but every solution I've attempted has only resulted in compiling errors.

D's set method is simply

D::set(string s){
   C::set(s);
   D::set(s);
}

Upvotes: 0

Views: 147

Answers (1)

Pete Becker
Pete Becker

Reputation: 76245

First, as pointed out in a comment, all of these member functions are private, so none of them can call any of the others. Assuming that that's a typo, and they are all in fact marked public (or each class is a friend of all the others, definitely not a good idea), this can be done in a fairly straightforward way.

In D::set() you want to call C::set(). That's easy. Just do it:

void D::set(string s) {
    C::set(s);
}

And now you want C::set() to call B::get(). You can't do that directly, because C doesn't know about B. But, since get() is a virtual function, you can call it and rely on virtual dispatch to get the only overrider, namely, B::get(). That is:

void C::set(string s) {
    std::string res = get();
}

That works because this particular C object is, in fact, part of a D object, and every D object has a B sub-object that overrides A::get(). In a plain old C object, that call to get() would call A::get().

Just to be clear: this is a very confusing class hierarchy, so don't be embarrassed about being lost. On the other hand, maybe being lost means that it's just too complicated, and that there's a design problem here.

Upvotes: 1

Related Questions