Note that there are some explanatory texts on larger screens.

plurals
  1. POHow do I remove code duplication between similar const and non-const member functions in abstract classes?
    primarykey
    data
    text
    <p>first of, this is a follow up question to this one: <a href="https://stackoverflow.com/questions/123758/how-do-i-remove-code-duplication-between-similar-const-and-non-const-member-func?rq=1">How do I remove code duplication between similar const and non-const member functions?</a></p> <p>Let's say, I have an abstract class, providing one pure virtual function:</p> <pre><code>class ICommand { public: virtual ~ICommand() {}; virtual int Execute() = 0; protected: ICommand() {}; };//class ICommand </code></pre> <p>And another class inheriting from this one:</p> <pre><code>class cCommand : public ICommand { public: cCommand() {}; virtual ~cCommand() {}; virtual int Execute() { int retval = 0; //do something and return appropriate error code return retval; } };//class cCommand </code></pre> <p>Now I need a pointer to an object of type ICommand, but with const data, like:</p> <pre><code>//using a smart pointer here would be better, but it shows the problem ICommand const * p = new cCommand(); int retval = p-&gt;Execute(); //won't compile </code></pre> <p>The problem is, I call a non const member function on a const object. So i either have to remove the const when creating pointer p (bad, I guess...) or I have to add a const member function Execute() to ICommand as well. After struggeling a little with the fact, that the user has to implement two functions than (not to mention what happens, if we add some other pure virtual functions to the base class...), I came up with the following solution:</p> <pre><code>class ICommand { public: virtual ~ICommand() {}; virtual int Execute() { //Scott Meyers way return static_cast&lt;const ICommand&amp;&gt;(*this).Execute(); } virtual int Execute() const = 0; protected: ICommand() {}; };//class ICommand </code></pre> <p>That seems to do the job quite well, but I'm not sure whether this a suitable solution to my problem. Neither I think this is very intuitive for the user as he always has to implement the const version of the pure virtual member function, but not the non const one.</p> <p>My actual question is, whether there are any side effects I might not have considered or if there is any better solution to this problem I might have overseen so far.</p> <p>Thanks in advance, René.</p>
    singulars
    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