I need to implement a mock for an interface that is defined something like:
class Foo
{
public:
void sendEvent(int id) const = 0;
}
My mock class needs to save all event id’s sent to the class. This is how I intended to do it.
class FooMock : Foo
{
private:
m_vector std::vector<int>;
public:
void sendEvent(int id) const {m_vector.push_back(id);}
}
But obviously the compiler refuses that construction. Are there any solutions to this (assuming the interface could not be changed)?
I realize that I can use two classes for this. But isn’t there a way to shut the compiler up and allow me to to this, similar to const_cast?
You can make the vector
mutableso that it can be modified from within const methods, like this:Note however that this makes the vector mutable from all methods. If you only want to write to it from a single method, a
const_castis less invasive, in that you cast the constness ofthisaway just for a single call:I’m being a bit pedantic here – inside a const method,
thishas the typeT const * const(so both the object being pointed to as well as the pointer itself are const). Theconst_castjust casts away the constness of the object, but not of the pointer.