I need to mock some classes using GoogleMock and change the base class implementation so that it creates actually an instance of this mocked one.
The base class is generated automatically along with some other classes that don't need to be mocked and all added in the same library.
The classes that need to be mocked are created through a factory, through which i intend to return the child class.
Can i "relink" with this new library which has implementation for already linked base class?
What i hope to achieve is get the instance of the base class from the unit-under-test and then cast it up to the mocked one.
Code example:
Original.hpp
class Base
{
private:
Base();
public:
virtual ~Base();
static std::shared_ptr<Base> createInstance();
}
Original.cpp
#include "Original.hpp"
...
std::shared_ptr<Base> Base::createInstance()
{
return std::shared_ptr<Base>(new Base());
}
...
Modified.hpp
class Derived : public Base
.....
Modified.cpp
#include "Original.hpp"
#include "Modified.hpp"
...
std::shared_ptr<Base> Base::createInstance()
{
return std::shared_ptr<Base>((Base*) new Derived());
}
So i want whenever the Base class is instantiated through createInstance anywhere in the project, the createInstance defined in Modified.cpp to be used instead, to return the Derived class.
OK, I think I understand more or less. If the library is already compiled you cannot change the implementation of that static factory method. If you provide your own implementation and try to link it with the existing lib you will have multiple definition (not allowed). What you can do is to add one layer to your application that will be responsible for this Base objects creation:
// existing implementation
class Base {
public:
virtual ~Base();
static std::shared_ptr<Base> createInstance() {
return std::shared_ptr<Base>(new Base());
}
private:
Base() {};
};
// new layer, part of your production code
class IYourFactory {
public:
virtual ~IYourFactory() = default;
virtual std::shared_ptr<Base> createInstance() = 0;
};
// new layer, part of your production code
class ProductionFactory: public IYourFactory {
public:
~ProductionFactory() override = default;
std::shared_ptr<Base> createInstance() override {
return Base::createInstance();
}
};
// testing code, you can use GMock to create this class
class MockBase: public Base {
public:
// it's a hack for Base private default constructor
MockBase(): Base(*Base::createInstance()) {}
~MockBase() override = default;
};
// testing code, you can use GMock to create this class
class MockFactory: public IYourFactory {
~MockFactory() override = default;
std::shared_ptr<Base> createInstance() override {
return std::make_shared<MockBase>();
}
};
class YourSystem {
public:
YourSystem(std::shared_ptr<IYourFactory> factory): factory_(factory) {}
bool doSomeThings() {
auto basePtr = factory_->createInstance();
return true;
}
private:
std::shared_ptr<IYourFactory> factory_;
};
Of course it will only do the job if Base class has some virtual functions that you can override in your MockBase. If not, this is not the way to go (you will need to create your own interface for the methods offered by Base).
The exact solution depends on how you use it in your system and what is the interface to Base.
Related
I'm trying to make a copy of a derived class with only a base class pointer.
So if I have:
class BaseClass; //Abstract class with =0 functions
class LeftClass : BaseClass;
class RightClass : BaseClass;
And I have a function that takes a BaseClass as a parameter:
void Function(BaseClass* baseClass)
I want to make a copy of BaseClass, but I want to also copy the extended functionality of LeftClass OR RightClass, but I don't know which one was passed to the function - both are possible.
So I have something like this:
//global
vector<BaseClass*> myVector;
void Function(BaseClass* baseClass)
{
BaseClass* baseClassCopy = new BaseClass(baseClass);
myVector.push_back(baseClassCopy);
}
And then I call the function with a left or right class
int main()
{
LeftClass leftClass;
Function(&leftClass);
LeftClass* ResultOfCopy = myVector.at(0);
}
That code doesn't copy over the entire leftclass as a copy, is there a way to do this I'm overlooking?
Also BaseClass is abstract, some of the functions are =0 so I can't new one up. Otherwise there is a copy function in the other classes to use.
If you can't change any of the classes to add a clone function then you can manually do that yourself by using dynamic_cast to determine its run time type and call the correct derived constructor. That would look like
void Function(BaseClass* baseClass)
{
if (auto ptr = dynamic_cast<LeftClass*>(baseClass))
myVector.push_back(new LeftClass(*ptr));
if (auto ptr = dynamic_cast<RightClass*>(baseClass))
myVector.push_back(new RightClass(*ptr));
}
and you can see it working in this live example
This kind of problem is usually solved by a clone() method.
class BaseClass
{
virtual BaseClass* clone() = 0
};
class LeftClass: public BaseClass
{
virtual LeftClass* clone() override {return new LeftClass(*this);}
};
class RightClass: public BaseClass
{
virtual RightClass* clone() override {return new RightClass(*this);}
};
class RightRightClass: public RightClass
{
virtual RightRightClass* clone() override {return new RightRightClass(*this);}
};
Your function is now easy to write:
void Function(BaseClass* baseClass)
{
BaseClass* baseClassCopy = !baseClass ? nullptr : baseClass->clone();
myVector.push_back(baseClassCopy);
}
I have a kind of "triangle inheritance" problem, if such a thing exists. Basically, I have an abstract base class the defines an interface, and a policy class that defines the implementation to part of that interface, like so:
class System
{
public:
Interface() = default;
virtual ~Interface() {}
virtual void doSomething() = 0;
virtual bool somethingDone() const = 0;
virtual int trait1() const = 0;
virtual bool trait2() const = 0;
};
class SomethingImplementation
{
public:
SomethingImplementation() = default;
void doSomething() { (void)0; }
bool somethingDone() { return true; }
};
And then I have several implementations of the interface for different cases. In some cases, I want to use the simple implementation, and in others I want to customize them
class SystemA : public System, public SomethingImplementation {/*...*/};
class SystemB : public System, public SomethingImplementation {/*...*/};
class SystemC : public System, { /* with a custom implementation ... */ };
What I can't figure out is what the details of class SystemA or SystemB might be to make the implementation work
http://cpp.sh/73r5
Solution 1
using statements, don't seem to do anything in this case.
http://cpp.sh/2nhki
59:13: error: cannot declare variable 'a' to be of abstract type 'SystemA'
22:7: note: because the following virtual functions are pure within 'SystemA':
6:18: note: virtual void System::doSomething()
7:18: note: virtual bool System::somethingDone() const
60:13: error: cannot declare variable 'b' to be of abstract type 'SystemB'
31:7: note: because the following virtual functions are pure within 'SystemB':
6:18: note: virtual void System::doSomething()
7:18: note: virtual bool System::somethingDone() const
63:38: error: invalid new-expression of abstract class type 'SystemA'
Solution 2
Add an extra interface class. Create a SomethingInterface class and inherit both Interface and SomethingImplementation from SomethingInterface. This turns the problem into a regular "diamond inheritance" problem, but I still can't seem to get the compiler to do what I want.
http://cpp.sh/3dxab
What is the way to use the implementation from another class for a virtual method of a parent class?
Every example I've seen of diamond inheritance was from bad design because of a misunderstanding of the IS-A and HAS-A relationships. Don't inherit to use an implementation, inherit to provide an implementation (e.g. inherit to implement).
SystemA should inherit from System and have a SomethingImplementation as a member whose methods it calls.
You might also look into mixins.
I believe you want to do something like this.
// The interface.
class IInterface
{
public:
virtual ~IInterface() {}
virtual void method1() = 0;
virtual void method2() = 0;
};
// A partial, abstract implementation of interface.
// This base class implements method1 but leaves method2 unimplemented,
// which means this class cannot be instantiated.
class PartialImplementation : public IInterface
{
public:
virtual void method1() {}
};
// Full implementation that uses the partial implementation above.
// method1's implementation is from the base class.
// method2's implementation is in this class.
// Because all methods are implemented (directly or inherited), this class can be instantiated.
class FullImplementation1 : public PartialImplementation
{
public:
void method2() {}
};
// Full implementation that uses the partial implementation above.
// method1's implementation is in this class (overrides base implementation).
// method2's implementation is in this class.
// Because all methods are implemented (directly), this class can be instantiated.
class FullImplementation2 : public PartialImplementation
{
public:
void method1() {}
void method2() {}
};
// Full implementation that DOES NOT use the partial implementation above.
// method1's implementation is in this class.
// method2's implementation is in this class.
// Because all methods are implemented (directly), this class can be instantiated.
class FullImplementation3 : public IInterface
{
public:
void method1() {}
void method2() {}
};
int main()
{
FullImplementation1 i1; // OK
FullImplementation2 i2; // OK
FullImplementation3 i3; // OK
IInterface* p1 = new FullImplementation1(); // OK
delete p1; // OK
IInterface* p2 = new FullImplementation2(); // OK
delete p2; // OK
IInterface* p3 = new FullImplementation3(); // OK
delete p3; // OK
return 0;
}
Suppose I have a base class which cloning of derived classes:
class Base
{
public:
virtual Base * clone()
{
return new Base();
}
// ...
};
I have a set of derived classes which are implemented using a curiously recurring template pattern:
template <class T>
class CRTP : public Base
{
public:
virtual T * clone()
{
return new T();
}
// ...
};
And I attempt to derive from that further like this:
class Derived : public CRTP<Derived>
{
public:
// ...
};
I get compilation errors to the effect of:
error C2555: 'CRTP<T>::clone': overriding virtual function return type differs and is not covariant from 'Base::clone'
I realize this is probably a result of the compiler not fully knowing the inheritance tree for Derived when instantiating CRTP. Furthermore, replacing the return type (T*) with (Base*) also compiles. However, I would like to know if there is a work around which retains the above semantics.
A not-so-pretty workaround.
class Base
{
protected:
virtual Base * clone_p()
{
return new Base();
}
};
template <class T>
class CRTP : public Base
{
protected:
virtual CRTP* clone_p()
{
return new T;
}
public:
T* clone()
{
CRTP* res = clone_p();
return static_cast<T*>(res);
}
};
class Derived : public CRTP<Derived>
{
public:
};
Use dynamic_cast<> instead of static if you feel it's safer.
If you can live with having to use a different syntax for specifying complete types, you might do the following (warning: untested code):
Let's first start with the machinery:
// this gives the complete type which needs to be used to create objects
// and provides the implementation of clone()
template<typename T> class Cloneable:
public T
{
public:
template<typename... U> Cloneable(U&&... u): T(std::forward<U>(u) ...) {}
T* clone() { return new Cloneable(*this); }
private:
// this makes the class complete
// Note: T:: to make it type dependent, so it can be found despite not yet defined
typename T::CloneableBase::CloneableKey unlock() {}
};
// this provides the clone function prototype and also makes sure that only
// Cloneable<T> can be instantiated
class CloneableBase
{
template<typename T> friend class Cloneable;
// this type is only accessible to Clonerable instances
struct CloneableKey {};
// this has to be implemented to complete the class; only Cloneable instances can do that
virtual CloneableKey unlock() = 0;
public:
virtual CloneableBase* clone() = 0;
virtual ~CloneableBase() {}
};
OK, now the actual class hierarchy. That one is pretty standard; no CRTP intermediates or other complications. However no class implements the clone function, but all inherit the declaration (directly or indirectly) from CloneableBase.
// Base inherits clone() from CloneableBase
class Base:
public CloneableBase
{
// ...
};
// Derived can inherit normally from Base, nothing special here
class Derived:
public Base
{
// ...
};
Here's how you then create objects:
// However, to create new instances, we actually need to use Cloneable<Derived>
Cloneable<Derived> someObject;
Derived* ptr = new Cloneable<Derived>(whatever);
// Now we clone the objects
Derived* clone1 = someObject.clone();
Derived* clone2 = ptr->clone();
// we can get rid og the objects the usual way:
delete ptr;
delete clone1;
delete clone2;
Note that a Cloneable<Derived> is-a Derived (it is a subclass), therefore you need to use Cloneable only for construction, and can otherwise pretend to work with Derived objects (well, tyepinfo will also identify it as Cloneable<Derived>).
I want to have a class hierarchy and be able to create objects from it only inside a Factory.
Example:
class Base
{
protected:
Base(){};
virtual void Init(){};
friend class Factory;
};
class SomeClass : public Base
{
public://I want protected here! Now it's possible to call new SomeClass from anywhere!
SomeClass(){};
void Init(){};
};
class Factory
{
public:
template<class T>
T* Get()
{
T* obj = new T();
obj->Init();
return obj;
}
};
int main()
{
Factory factory;
SomeClass *obj = factory.Get<SomeClass>();
}
My problem is that I want to be able to make objects only from Factory, but I don't want to declare friend class Factory in every class derived from Base.
Is there any way to propagate friend in derived classes? Is there any other way to achieve this behavior?
No, it's deliberately impossibile.
Is an issue by encapsulation.
Suppose to have a class "PswClass" that manage any password, that is cascade friend with other class: if I inherit from PswClass:
class Myclass : public PswClass {
.......
}
In this way I can, maybe, have access to field that it would be private.
Friendship is neither inherited nor transitive, as described here: friend class with inheritance.
After a little experimentation, and making some use of this hack How to setup a global container (C++03)?, I think I have found a way give the "factory" unique rights to create the objects.
Here's a quick and dirty code. (Scroll towards the bottom to see the hack.)
class Object {};
class Factory {
public:
// factory is a singleton
// make the constructor, copy constructor and assignment operator private.
static Factory* Instance() {
static Factory instance;
return &instance;
}
public: typedef Object* (*CreateObjectCallback)();
private: typedef std::map<int, CreateObjectCallback> CallbackMap;
public:
// Derived classes should use this to register their "create" methods.
// returns false if registration fails
bool RegisterObject(int Id, CreateObjectCallback CreateFn) {
return callbacks_.insert(CallbackMap::value_type(Id, createFn)).second;
}
// as name suggests, creates object of the given Id type
Object* CreateObject(int Id) {
CallbackMap::const_iterator i = callbacks_.find(Id);
if (i == callbacks_.end()) {
throw std::exception();
}
// Invoke the creation function
return (i->second)();
}
private: CallbackMap callbacks_;
};
class Foo : public Object {
private: Foo() { cout << "foo" << endl; }
private: static Object* CreateFoo() { return new Foo(); }
public:
static void RegisterFoo() {
Factory::Instance()->RegisterObject(0, Foo::CreateFoo);
}
};
class Bar : public Object {
private: Bar() { cout << "bar" << endl; }
private: static Object* CreateBar() { return new Bar(); }
public:
static void RegisterBar() {
Factory::Instance()->RegisterObject(1, Bar::CreateBar);
}
};
// use the comma operator hack to register the create methods
int foodummy = (Foo::RegisterFoo(), 0);
int bardummy = (Bar::RegisterBar(), 0);
int main() {
Factory::Instance()->CreateObject(0); // create foo object
Factory::Instance()->CreateObject(1); // create bar object
}
No, there is no way to inherit friend declaration from base class. However, if you make Base constructor private, instances of derived classes won't be possible to create without Factory help.
As others already said, friendship is not inheritable.
this looks like a good candidate of "Abstract Factory" pattern.
assume "SomeClass"es derived from base are used polymorphically.
declare a abstract factory base, which creates Base objects.
derive each concrete factory from base, override the base creation method...
see http://en.wikipedia.org/wiki/Abstract_factory_pattern for examples
You can't do that. This is done to protect encapsulation. See this post: Why does C++ not allow inherited friendship?
For future reference, another idea that came out of the chat between OP and me, which works with only one use of friend as the OP wanted. Of course, this is not a universal solution, but it may be useful in some cases.
Below code is a minimal one which shows the essential ideas. This needs to be "integrated" into the rest of the Factory code.
class Factory;
class Top { // dummy class accessible only to Factory
private:
Top() {}
friend class Factory;
};
class Base {
public:
// force all derived classes to accept a Top* during construction
Base(Top* top) {}
};
class One : public Base {
public:
One(Top* top) : Base(top) {}
};
class Factory {
Factory() {
Top top; // only Factory can create a Top object
One one(&top); // the same pointer could be reused for other objects
}
};
It is not possible. As others have said friendship is not inherited.
An alternative is to make all class hierarchy constructors protected and add the factory function/class as friend to all the classes you're interested in.
I'm trying to solve a problem where I have some classes in which I need to do some common work and then a bunch of problem specific work and when this is finished do some more processing common to all these classes.
I have a Base and Derived class that both have a function called Execute. When I call the derived version of this function, I'd like to be able to do some processing common to all my derived classes in the Base and then continue executing in my Derived::Execute and going back to Base::Execute to finish off with some common work.
Is this possible in C++ and how would one best go about doing that?
This is the idea, however it's probably not very workable like this:
class Base
{
public:
virtual void Execute();
};
Base::Execute() {
// do some pre work
Derived::Execute(); //Possible????
// do some more common work...
}
class Derived : public Base
{
public:
void Execute();
};
void Derived::Execute()
{
Base::Execute();
//Do some derived specific work...
}
int main()
{
Base * b = new Derived();
b.Execute(); //Call derived, to call into base and back into derived then back into base
}
Use a pure virtual function from base..
class Base
{
public:
void Execute();
private:
virtual void _exec() = 0;
};
Base::Execute() {
// do some common pre work
// do derived specific work
_exec();
// do some more common work...
}
class Derived : public Base
{
private:
void _exec() {
// do stuff
}
};
int main()
{
Base * b = new Derived();
b.Execute();
}
EDIT: changed the flow slightly after reading the question some more.. :) The above mechanism should match exactly what you require now -
i.e.
Base Common Stuff
Derived specific stuff
Base Common stuff again
This is called the NVI (Non-Virtual Interface, from Herb Sutter here) idiom in C++, and basically says that you should not have public virtual functions, but rather protected/private virtual functions. User code will have to call your public non-virtual function in the base class, and that will dispatch through to the protected/private virtual method.
From a design perspective the rationale is that a base class has two different interfaces, on one side the user interface, determined by the public subset of the class, and on the other end the extensibility interface or how the class can be extended. By using NVI you are decoupling both interfaces and allowing greater control in the base class.
class base {
virtual void _foo(); // interface to extensions
public:
void foo() { // interface to users
// do some ops
_foo();
}
};
Turn the problem from its head to its feet. What you actually want to have is a base class algorithm that derived classes can plug into:
class Base {
public:
void Execute()
{
// do something
execute();
// do some more things
}
private:
virtual void execute() = 0;
};
class Derived : public Base {
public:
// whatever
private:
virtual void execute()
{
//do some fancy stuff
}
};
Letting derived classes plug into base class algorithms is often called "template method" pattern (which has nothing to do with template. Having no public virtual functions in the base class interface is often called "non-virtual interface" pattern.
I'm sure google can find you a lot on those two.
Move that Base::Execute internally in two functions and then use RAII to implement that easily.
class Base{
protected:
void PreExecute(){
// stuff before Derived::Execute
}
void PostExecute(){
// stuff after Derived::Execute
}
public:
virtual void Execute() = 0;
};
struct ScopedBaseExecute{
typedef void(Base::*base_func)();
ScopedBaseExecute(Base* p)
: ptr_(p)
{ ptr_->PreExecute() }
~ScopedBaseExecute()
{ ptr_->PostExecute(); }
Base* ptr_;
};
class Derived : public Base{
public:
void Execute{
ScopedBaseExecute exec(this);
// do whatever you want...
}
};