-2

Trying to achieve a design where the classes that implement interfaces should only be callable from a Library. In other words, the access to the implemented interfaces should be through the library (TopLib). Seems like the case where delegate should be used. What do you think of the design ? This works, but would appreciate feedback and suggestions on making it better and robust and fool proof.

class Interface 
{
protected:
    virtual void hi(void) = 0;
};

class ABC : private Interface {
protected:
    ABC() {}
    virtual void hi() {
        std::cout << "abc" << std::endl;
    }
};

class XYZ : private Interface {
protected:
    XYZ() {}
    virtual void hi() {
        std::cout << "xyz" << std::endl;
    }
};

template<typename T>
class TopLib : private T
{
public:
    void sayhi() {
        hi();
    }
};

int _tmain(int argc, _TCHAR* argv[])
{
    TopLib<ABC> b;
    b.sayhi();

    TopLib<XYZ> c;
    c.sayhi();
    //c.hi(); <- fails

    //ABC test; <- fails
    //test.hi(); <- fails

    getchar();
    return 0;
}
Puppy
  • 144,682
  • 38
  • 256
  • 465
Vibgy
  • 577
  • 6
  • 15
  • Your title says C, but your tags and code say C++. Which is it? – Flexo Jan 29 '13 at 20:00
  • It's obviously Microsoft C++. – ipc Jan 29 '13 at 20:01
  • Doesn't `c.hi();` fail anyway? `hi()` is a protected member. – imreal Jan 29 '13 at 20:02
  • 3
    The real question is: What should it be good for? Right now I do not see how it would make the use of your library any better or easier. – bikeshedder Jan 29 '13 at 20:04
  • This code works. Would like to know if there are better ways of making sure that main program talks to interface implementation only through the library. Any other optimizations if possible would also help. – Vibgy Jan 29 '13 at 20:14

1 Answers1

1

Access modifiers can be relaxed in derived classes, so you are at the mercy of the one who implements the interface. There's nothing stopping me from saying

class FooBarBaz : private Interface {
  public:
    FooBarBaz() {}
    virtual void hi() { // Implements Interface::hi()
        std::cout << "see what i mean!" << std::endl;
    }
};

and using it with or without TopLib<FooBarBaz>.

Oswald
  • 31,254
  • 3
  • 43
  • 68
  • Thank you Oswald. I guess you are saying, I could use "class XYZ : protected Interface" ? instead of private ? – Vibgy Jan 29 '13 at 20:25
  • And is there a way to get around this? – Vibgy Jan 29 '13 at 20:28
  • Especially, I am saying someone can implement your interface using `public: virtual void hi()`. I don't know how to get around this "problem", but actually I do not see why this is a problem. Like bikeshedder said: What should it be good for? – Oswald Jan 29 '13 at 20:36
  • Got it. As long as someone implementing the interface is careful, main program wont be able to access that interface directly, and the design goal is basically achieved. Thanks for all the inputs guys. – Vibgy Jan 29 '13 at 21:13