Reputation: 153
first of, this is a follow up question to this one: How do I remove code duplication between similar const and non-const member functions?
Let's say, I have an abstract class, providing one pure virtual function:
class ICommand
{
public:
virtual ~ICommand() {};
virtual int Execute() = 0;
protected:
ICommand() {};
};//class ICommand
And another class inheriting from this one:
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
Now I need a pointer to an object of type ICommand, but with const data, like:
//using a smart pointer here would be better, but it shows the problem
ICommand const * p = new cCommand();
int retval = p->Execute(); //won't compile
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:
class ICommand
{
public:
virtual ~ICommand() {};
virtual int Execute()
{ //Scott Meyers way
return static_cast<const ICommand&>(*this).Execute();
}
virtual int Execute() const = 0;
protected:
ICommand() {};
};//class ICommand
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.
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.
Thanks in advance, René.
Upvotes: 0
Views: 170
Reputation: 101476
Yes, if you want a user to call a method you provide with either a const
or a non-const
this
pointer, then you must provide at least a const
version of the function to call. Note that you can call a const
method with a non-const
this
pointer.
Consider if Execute
needs to be non-const
at all. There is at least a non-zero chance that if you are able to provide a const
version of Execute
, then the nonconst
version of Execute
is totally unnecessary.
So, in direct response to your question:
How do I remove code duplication between similar const and non-const member functions in abstract classes?
Maybe by eliminating the non-const
member function altogether.
Upvotes: 3