Note that there are some explanatory texts on larger screens.

plurals
  1. POAdding Functionality To An Object Without Changing The Interface
    primarykey
    data
    text
    <p>I have an object presented as a reference/pointer to an interface. I would like to call a method on the concrete object if that method is present, without changing the interface, breaking encapsulation, or writing any horrible hacks. How can it be done?</p> <p>Here's an example.</p> <p>I have an interface:</p> <pre><code>class IChatty { public: virtual ~IChatty() {}; virtual std::string Speak() const = 0; }; </code></pre> <p>And multiple concrete implementation of this interface:</p> <pre><code>class SimpleChatty : public IChatty { public: ~SimpleChatty() {}; virtual std::string Speak() const override { return "hello"; } }; class SuperChatty : public IChatty { public: void AddToDictionary(const std::string&amp; word) { words_.insert(word); } virtual std::string Speak() const override { std::string ret; for(auto w = words_.begin(); w != words_.end(); ++w ) { ret += *w; ret += " "; } return ret; } private: std::set&lt;std::string&gt; words_; }; </code></pre> <p>The <code>SuperChatty::AddToDictionary</code> method is not present in the abstract <code>IChatty</code> interface, although it could be included in another, new interface.</p> <p>In the real world, these objects are constructed through factories, themselves concrete instantiations of an abstract interface. However for our purposes that's orthogonal to the problem at hand:</p> <pre><code>int main() { IChatty* chatty = new SuperChatty; chatty-&gt;AddToDictionary("foo"); std::cout &lt;&lt; chatty-&gt;Speak() &lt;&lt; std::endl; } </code></pre> <p>Since <code>AddToDictionary</code> isn't part of the <code>IChatty</code> interface (and <em>can't</em> be part of it), I can's call it.</p> <p>How can I call <code>AddToDictionary</code> on the <code>chatty</code> pointer without breaking encapsulation, writing some horrible hack, or taking any other design shortcuts?</p> <p>NOTE: In the real world, the dictionary is part of the <code>SuperChatty</code> object itself, and cannot be separate from it.</p> <p>NOTE2: I do not want to downcast to the concrete type.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload