I want to use mock object to test my class which uses shared_ptr pointer.
It likes ,
struct MyInterface {
// public functions
};
class MyClass {
public:
MyClass (shared_ptr<MyInterface> handle) : m_handle(handle) {}
~MyClass() {}
// ...
private :
shared_ptr<MyInterface> m_handle;
}
When I test MyClass, I pass a mock object to it.
struct NullDeleter {template<typename T> void operator()(T*) {} };
TMockObject<MyInterface> * mock = new TMockObject<MyInterface>();
shared_ptr<MyInterface> handle((MyInterface*)(*mock), NullDeleter());
MyClass myClass(handle);
delete mock;
the question is I have to use a NullDeleter when i create the shared pointer, otherwise, mock will be delete as a MyInterface which cause error.
Is there any better design for this ?
thanks~
If I could understand what you want to do and I do not take the mistake,
I prefer to have method inside myClass class to check proper value of argument.
It means, you should after pass your argument to class constructor, provide another method to check the value.
Add a virtual destructor to MyInterface, and then when you delete an (abstract) MyInterface, all the sub class destructor is invoked as well.
struct MyInterface {
virtual ~MyInterface() { }
// public functions
};
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);
}
Suppose we want to implement strategy pattern. We have an interface Base and two derived classes -- A and B. Instances of Doer class can choose between A's and B's methods do(). And the question is how to complete the code to make how it should be.
class Base {
virtual void do() const = 0;
};
class A: public Base {
void do() const override {};
};
class B: public Base {
void do() const override {};
}
class Doer {
public:
Doer(std::unique_ptr<Base> b_ptr) : ptr(b_ptr) {}
void do() const { ptr->do(); }
private:
std::unique_ptr<Base> ptr;
}
int main() {
Doer doer(std::unique_ptr<Base>());
doer.do();
return 0;
}
Doer doer(std::make_unique<A>()); // or std::make_unique<B>()
The above is pretty much it. std::unique_ptr works very hard to implement the same coercion as the raw pointer it holds.
There are three major problems with your code.
1) do is a keyword of the language. You cannot use it as an identifier (like function name)
2) you take b_ptr by value, so you need to move from it:
Doer(std::unique_ptr<Base> b_ptr) : ptr(std::move(b_ptr)) {}
3) you pass an empty unique_ptr to Doer's constructor, which is equivalent to passing a nullptr. You also try to instantiate the base class. It is impossible because Base is a pure virtual class. Use make_unique with a derived type:
Doer doer(std::make_unique<A>());
I have a weird C++ problem where I'm not sure if it works correctly this way or If I missed something.
There is a class A which inherits from ABase. ABase and A both have a method Generate() while A::Generate() should overwrite ABase::Generate().
Generate() is called out of the constructor of ABase.
Now my problem:
I do a new A() which first jumps into constructor of A and from there into constructor of ABase. ABase::ABase() now calls Generate(). What I want to do: A::Generate() should be executed (since this overwrites ABase::Generate()).
Unfortunately it seems out of the constructor of ABase only ABase::Generate() is called and never A::Generate().
I gues that happens because A is not fully constructed at this stage? Or is there a way to let ABase::ABase() make use of A::Generate()?
You do not want A::Generate() to be executed, since this
would involve executing a function on a class which has not been
constructed. C++ has been designed intentionally so that during
construction, the dynamic type of the object is the type being
constructed, precisely to avoid this sort of problem.
It's not easy to work around, and definitely not pretty, but you may be able to do something like this:
class ABase
{
public:
ABase()
{
// Normal constructor, calls `Generate`
}
virtual void Generate() { ... }
// ...
protected:
struct do_not_call_generate_tag {};
const static do_not_call_generate_tag do_not_call_generate;
ABase(const do_not_call_generate_tag)
{
// Same as the normal `ABase` constructor, but does _not_ call `Generate`
}
};
class A : public ABase
{
public:
A()
: ABase(ABase::do_not_call_generate)
{
// Other initialization
PrivateGenerate();
}
void Generate()
{
PrivateGenerate();
}
private:
void PrivateGenerate()
{
// Do what your old `Generate` does
}
};
In order to have nicely constructed and initialized objects, I would separate these two tasks from each other:
class ABase
{
public:
virtual void Generate()
{
//...
}
};
class A: public ABase
{
public:
virtual void Generate()
{
//...
}
};
Now you have to perform both tasks explicitly
A *someA = new A();
someA->Generate();
...but you can group this inside e.g. a Create() method or redefine the new operator or the like.
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 want to instantiate a base class pointer to point to a newly constructed derived class object. The actual class for the object will change depending on the application type, so I want to use a Factory method to switch on certain variables in order to construct the right object.
However I don't want to have to do the switch each time. In fact, once the application starts, the type of object I want to create in this situation will always be the same - so actually I only need to do this switch only once.
Can I pass in a derived class Constructor to the function creating the object?
For example:
typedef DerivedObject (*DerivedClassConstructor)( void );
class ContainingClass:
{
public:
ContainingClass ( DerivedClassConstructor * f )
{
baseptr = f();
}
BaseClass * baseptr
};
Is there a better design?
Would it not be easier to templatise the code.
That way it looks like normal code.
class BaseClass
{};
class Derived: public BaseClass
{};
template<typename T>
class ContainingClass
{
public:
ContainingClass()
{
baseptr = new T();
}
BaseClass * baseptr;
};
int main()
{
ContainingClass<Derived> cont;
}
I think that's pretty sane. Just pass a function object and save it since it seems you need to recall it later (otherwise why not pass the pointer directly and create the object before?)
class ContainingClass:
{
public:
typedef boost::function<BaseClass*()> factory_fn;
public:
ContainingClass (factory_fn f )
:m_f(f)
{
baseptr = m_f();
}
BaseClass * baseptr
factory_fn m_f;
};
template<typename T>
struct DerivedFactory {
BaseClass *operator()() {
return new T;
}
};
ContainingClass c((DerivedFactory<DerivedClass>()));
You can't do it with a constructor, since a constructor is not actually returning a class instance.
You talk about a factory method, and you got half way towards actually using one. However, it is not a good idea to create a dependency from base class to derived class - why can't your factory method simply return (a pointer to) BaseClass objects?
typedef BaseClass* (*BaseClassFactory)( void );