How to mock constructors and destructor with gmock - c++

I need to count how many times constructors(default/copy/move) and destructor have been called. I use gmock. How can i check it?
EDIT: Thanks to Marko Popovic suggestion i will explain that i have for now. I have a class like this, and i want to mock it with gmock. How can i do this?
class A
{
public:
static int m_calls_to_cons;
public:
A( ) { m_calls_to_cons++; }
};
int A::m_calls_to_cons;
I use this class to check behavior of my container.

First, you must specify what you need. The way to do this is by defining interface class:
class SpecialFunctionsNotifier
{
public:
virtual ~SpecialFunctionsNotifier() {}
virtual void construct() = 0;
virtual void destruct() = 0;
virtual void copyConstruct() = 0;
virtual void copyAssign() = 0;
};
So, you can make "default" null (meaning empty) object implemention:
class SpecialFunctionsNullNotifier : public SpecialFunctionsNotifier
{
public:
virtual void construct() override {}
virtual void destruct() override {}
virtual void copyConstruct() override {}
virtual void copyAssign() override {}
};
And, have A use of it:
class A
{
public:
static SpecialFunctionsNullNotifier m_calls_to_cons_default;
static SpecialFunctionsNotifier* m_calls_to_cons;
public:
A( ) { m_calls_to_cons->construct(); }
};
SpecialFunctionsNullNotifier A::m_calls_to_cons_default;
SpecialFunctionsNotifier* A::m_calls_to_cons = &A::m_calls_to_cons_default;
Then, mocking this notifies is easy task:
class SpecialFunctionsNotifierMock : public SpecialFunctionsNotifier
{
public:
MOCK_METHOD0(construct, void());
// ..
};
And in your tests, use in this way:
TEST(ACase, AConstructCount)
{
SpecialFunctionsNotifierMock callToConsMock;
A::m_calls_to_cons = &callToConsMock;
EXPECT_CALL(callToConsMock, construct()).Times(100);
A a[100];
// remember to cleanup
A::m_calls_to_cons = &A::m_calls_to_cons_default;
}

Related

How to properly override function with different arguments in derived class?

I'm making a simple MVC example for c++ classes at my uni. First, look at the code:
The executor.h part:
class IExecutor {
IParams params;
public:
virtual void initialize(IParams iParams);
virtual void execute();
};
class QEExec : public IExecutor {
public:
void initialize(QEParams iParams) override;
void execute() override;
};
And now params.h part:
class IParams {
};
class QEParams : public IParams {
public:
int a;
int b;
int c;
};
The problem is that I want to create void initialize(QEParams iParams) function for QEExec and pass QEParams to it in order to have access to a, b, and c parameters (I'll need that later) but I can't do so because of virtual void initialize(IParams). I thought that if QEParams is derives from IParams I will be able to do so, but I can't access parameters that I mentioned earlier. How to make it work so that I'll be able to access a, b and c parameters in initialize function?
EDIT: I'll put a photo of how it should look like:
https://i.stack.imgur.com/KWaSQ.jpg
Interface doesn't have any fields
Interface has only pure virtual methods
Name initialize of IExecutor indicates some misunderstanding. Looks like it suppose to be called once at the begging during construction time. It should be hidden in step where some factory creates object implementing IExecutor
So basically I'm suspecting you need more something like this:
class IExecutor
{
public:
virutal ~IExecutor() {}
virtual void execute() = 0;
};
struct QEParams {
int a;
int b;
int c;
};
class QEExec: public IExecutor
{
public:
QEExec(int b, int c) ....
void initialie(); // second step init
void execute() override;
};
class CAExec: public SomeOtherBaseClass, public IExecutor
{
public:
CAExec(int a, int c) ....
void execute() override;
};
std::unique_ptr<IExecutor> executorFactory(const QEParams& params)
{
if (params.a < 0) {
auto result = std::make_unique<QEExec>(params.b, params.c);
result->initialie();
return result;
}
return std::make_unique<CAExec>(params.a, params.c);
}
Usually factory parameters are structural data and extra abstraction is obsolete.
If different kind of arguments are needed to create alternative version of IExecutor you just provide different factory function (possibly overload):
std::unique_ptr<IExecutor> executorFactory(const std::string& fileName)
{
....
}
It sounds like you're using OOP incorrectly.
Since QEExec is a IExecutor (it inherits), and it can initialize just like IExecutor can, ideally, both of those initialize's will be doing similar things to their IParams objects. If so, then the one who should be acting on a, b and c should be QEParams, not QEExec.
You could do this with polymorphism like:
class IParams {
virtual void init_logic() { }
};
class QEParams : public IParams {
public:
void init_logic() { /* Do something with a/b/c */ }
private:
int a;
int b;
int c;
};
And then...
class IExecutor {
IParams params;
public:
virtual void initialize(IParams *iParams);
virtual void execute();
};
class QEExec : public IExecutor {
public:
//Will call the QEParams init_logic when passed a QEParams pointer
void initialize(IParams *iParams) { iParams->init_logic(); }
void execute() override;
};

How do you call a virtual method stored in the base class and called by a class that inherits that base class twice?

This code demonstrates the problem:
class Base
{
public:
explicit Base(std::function<void()> const& printFunc) :
_printFunc(printFunc)
{
}
void print()
{
_printFunc();
}
private:
std::function<void()> _printFunc{};
private:
virtual void _print() = 0; // If this line is commented out, then
// `Subclass1::_print()` can be called.
};
class Subclass1 : public Base
{
public:
explicit Subclass1() :
Base([this]() { _print(); })
{
}
private:
void _print() /*override*/
{
std::cout << "Subclass1\n";
}
};
class Subclass2 : public Base, public Subclass1
{
public:
using fromLowestSubclass = Base;
public:
explicit Subclass2() :
Base([this]() { _print(); }), Subclass1()
{
}
private:
void _print() /*override*/
{
// Here is the problem:
Subclass1::print(); // or: static_cast<Subclass1*>(this)->print();
std::cout << "Subclass2\n";
}
};
int main()
{
Subclass2 sc2{};
sc2.fromLowestSubclass::print();
return 0;
}
In the Subclass2::_print method, the overriding _print method of Subclass1 should be called, but instead the Subclass1::print(); statement calls the current method again. This problem can be prevented if the statement virtual void _print() = 0; is commented out.
Why use of the virtual _print method prevents me from invoking the overloaded virtual method Subclass1::_print and what solution is there so that I do not have to do without virtual methods?
class Base
{
....
private:
virtual void _print() = 0;
}
This means: you can override _print, but you can't call it, only Base has right to call it.
Now:
class Base
{
public:
void print()
{
_printFunc();
}
does that, it calls _printFunc as a virtual function, which matches current object instantiation. It doesn't meter how print() was invoked.
Adding Subclass1:: as a prefix just changes name scope and doesn't have impact how method behaves. It has only have impact on name scope.
Now if virtual method has such prefix, then selecting name scope instruct compiler that you abandoning abstraction and you need to call specific method. In such case method is called without referring to a virtual table.
Double inheritance has no impact on this issue.
You can provide a helper method which you will be able to call from ancestor:
class Subclass1 : public Base
{
....
protected:
void sub1_print() // not virtual
{
std::cout << "Subclass1\n";
}
private:
void _print() /*override*/
{
sub1_print();
}
};
class Subclass2 : public Base, public Subclass1
{
....
private:
void _print() /*override*/
{
sub1_print();
std::cout << "Subclass2\n";
}
};

Defining a virtual method inherited more than once

I've been trying to find an answer to this question but I couldn't (I don't even know how to properly formulate this) so I decided to write my first post ever on StackOverflow =).
The context is the following:
I have this parent class:
class Parent
{
public:
Parent(){};
void foo(void)
{
//Do some common things
bar();
//Do some more common things
};
protected:
virtual void bar(void) = 0;
};
And I want to create an indefinite amount of derived Childs:
class Child1 : public Parent
{
public:
Child1() : Parent(), child1Variable(0) {};
protected:
virtual void bar(void) = 0;
private:
uint32_t child1Variable;
};
class Child2 : public Parent
{
public:
Child2() : Parent(), child2Variable(0) {};
protected:
virtual void bar(void) = 0;
private:
uint32_t child2Variable;
};
.
.
.
class ChildN : public Parent
{
public:
ChildN() : Parent(), childNVariable(0) {};
protected:
virtual void bar(void) = 0;
private:
uint32_t childNVariable;
};
The reason being mainly not repeating the code in Parent's foo()
Then I would like to create my final instantiable classes as, for instance:
class ExampleFinal : public Child1, public Child3, public Child27
{
//How to define Child1::bar(), Child3::bar() and Child27::bar() ??
private:
void bar(void); //????
};
So the questions are:
How can I define the method for (abusing notation) ExampleFinal::Child1::bar, ExampleFinal::Child3::bar, ...
Am I so stuck on this that I'm overlooking a much simpler solution?
The final goal is being able to do something like:
ExampleFinal test;
test.Child1::foo(); //should end up on "ExampleFinal::Child1::bar"
test.Child3::foo(); //should end up on "ExampleFinal::Child3::bar"
Thanks!
Implementing ExampleFinal::bar() (side-note: bar(void) is a C-ism which has no use in C++) will override all of the bars you have declared at once. If you want to have different versions, you'll need to interpose another layer of classes:
struct GrandChild1 : Child1 {
void bar() override { /*...*/ }
};
// And so on...
struct ExampleFinal : GrandChild1, GrandChild3, GrandChild27 {
// Nothing needed here.
};
Then the behaviour you described will work. Be aware, though, that your inheritance graph means that an ExampleFinal has one Parent subobject per Child. This is not an issue in itself but might not model what you want -- maybe you need virtual inheritance here, but beware of the rabbit hole.
If you want to keep the overrides for all ChildN::bars inside ExampleFinal, you can add tag-dispatching to discern them, at the cost of one more virtual call:
struct Parent {
void foo() {
bar();
};
protected:
template <class Child>
struct tag { };
virtual void bar() = 0;
};
struct Child1 : Parent {
protected:
virtual void bar(tag<Child1>) = 0;
void bar() final override {
return bar(tag<Child1>{});
}
int child1Var;
};
struct Child2 : Parent {
protected:
virtual void bar(tag<Child2>) = 0;
void bar() final override {
return bar(tag<Child2>{});
}
int child2Var;
};
struct ExampleFinal : Child1, Child2 {
protected:
using Parent::tag;
void bar(tag<Child1>) final override {
std::cout << "Child1::bar\n";
}
void bar(tag<Child2>) final override {
std::cout << "Child2::bar\n";
}
};
Note that the bar() to bar(tag<ChildN>) bridge can easily be hidden behind a macro. If you want to avoid the cost of the second virtual call, a CRTP can also be applied here.

Must Invoke first design pattern

I am looking for an elegant solution for my case. I tried to find a design pattern that specified and offers solution for this case but i failed to find one.
I have a base class that uses to store general object and later Invoke it.
I want the execution will be separated into two parts:
A must have part which will always take place (do1st()).
User defined code (do2nd()).
For example:
class InvokeBase
{
public:
InvokeBase(void *ptr) : context_(ptr) {}
virtual ~InvokeBase () {}
void operator()() = 0;
protected:
void do1st() {//Mandatory code to execute for every InvokeBase type when calling operator()};
void * context_;
};
class InvokeDerived : public InvokeBase
{
public:
InvokeDerived(void *ptr) : base(ptr){}
virtual ~InvokeDerived();
void do2nd() {//User defined code}
void operator()()
{
do1st(); // << How to force this execution?
do2nd();
}
};
void main()
{
InvokeBase *t = new InvokeDerived();
t(); // << here i want the execution order will be do1st and then do2nd.
}
The trick is that i want do1st will execute always, that i will not have to call it from InvokeDerived. I want to allow the user to inherit from InvokeBase with the guarantee that do1st will always be called when invoking the operator().
This is the template method pattern: split a function with semi-flexible behavior accross the class hierarchy into multiple parts, and make virtual only the ones that change:
class InvokeBase
{
public:
InvokeBase(void *ptr) : context_(ptr) {}
virtual ~InvokeBase () {}
void operator()() // this is non-virtual (this is the template method)
{
do1st();
do2nd(); // this resolves to virtual call
}
protected:
void do1st() { /* fixed code here */ };
virtual void do2nd() = 0; // variable part here
void * context_;
};
class InvokeDerived : public InvokeBase
{
public:
InvokeDerived(void *ptr) : base(ptr){}
virtual ~InvokeDerived() = default;
protected:
void do2nd() override
{
// code speciffic to InvokeDerived here
}
};

Inherit interfaces which share a method name

There are two base classes have same function name. I want to inherit both of them, and over ride each method differently. How can I do that with separate declaration and definition (instead of defining in the class definition)?
#include <cstdio>
class Interface1{
public:
virtual void Name() = 0;
};
class Interface2
{
public:
virtual void Name() = 0;
};
class RealClass: public Interface1, public Interface2
{
public:
virtual void Interface1::Name()
{
printf("Interface1 OK?\n");
}
virtual void Interface2::Name()
{
printf("Interface2 OK?\n");
}
};
int main()
{
Interface1 *p = new RealClass();
p->Name();
Interface2 *q = reinterpret_cast<RealClass*>(p);
q->Name();
}
I failed to move the definition out in VC8. I found the Microsoft Specific Keyword __interface can do this job successfully, code below:
#include <cstdio>
__interface Interface1{
virtual void Name() = 0;
};
__interface Interface2
{
virtual void Name() = 0;
};
class RealClass: public Interface1,
public Interface2
{
public:
virtual void Interface1::Name();
virtual void Interface2::Name();
};
void RealClass::Interface1::Name()
{
printf("Interface1 OK?\n");
}
void RealClass::Interface2::Name()
{
printf("Interface2 OK?\n");
}
int main()
{
Interface1 *p = new RealClass();
p->Name();
Interface2 *q = reinterpret_cast<RealClass*>(p);
q->Name();
}
but is there another way to do this something more general that will work in other compilers?
This problem doesn't come up very often. The solution I'm familiar with was designed by Doug McIlroy and appears in Bjarne Stroustrup's books (presented in both Design & Evolution of C++ section 12.8 and The C++ Programming Language section 25.6). According to the discussion in Design & Evolution, there was a proposal to handle this specific case elegantly, but it was rejected because "such name clashes were unlikely to become common enough to warrant a separate language feature," and "not likely to become everyday work for novices."
Not only do you need to call Name() through pointers to base classes, you need a way to say which Name() you want when operating on the derived class. The solution adds some indirection:
class Interface1{
public:
virtual void Name() = 0;
};
class Interface2{
public:
virtual void Name() = 0;
};
class Interface1_helper : public Interface1{
public:
virtual void I1_Name() = 0;
void Name() override
{
I1_Name();
}
};
class Interface2_helper : public Interface2{
public:
virtual void I2_Name() = 0;
void Name() override
{
I2_Name();
}
};
class RealClass: public Interface1_helper, public Interface2_helper{
public:
void I1_Name() override
{
printf("Interface1 OK?\n");
}
void I2_Name() override
{
printf("Interface2 OK?\n");
}
};
int main()
{
RealClass rc;
Interface1* i1 = &rc;
Interface2* i2 = &rc;
i1->Name();
i2->Name();
rc.I1_Name();
rc.I2_Name();
}
Not pretty, but the decision was it's not needed often.
You cannot override them separately, you must override both at once:
struct Interface1 {
virtual void Name() = 0;
};
struct Interface2 {
virtual void Name() = 0;
};
struct RealClass : Interface1, Interface2 {
virtual void Name();
};
// and move it out of the class definition just like any other method:
void RealClass::Name() {
printf("Interface1 OK?\n");
printf("Interface2 OK?\n");
}
You can simulate individual overriding with intermediate base classes:
struct RealClass1 : Interface1 {
virtual void Name() {
printf("Interface1 OK?\n");
}
};
struct RealClass2 : Interface2 {
virtual void Name() {
printf("Interface2 OK?\n");
}
};
struct RealClass : RealClass1, RealClass2 {
virtual void Name() {
// you must still decide what to do here, which is likely calling both:
RealClass1::Name();
RealClass2::Name();
// or doing something else entirely
// but note: this is the function which will be called in all cases
// of *virtual dispatch* (for instances of this class), as it is the
// final overrider, the above separate definition is merely
// code-organization convenience
}
};
Additionally, you're using reinterpret_cast incorrectly, you should have:
int main() {
RealClass rc; // no need for dynamic allocation in this example
Interface1& one = rc;
one.Name();
Interface2& two = dynamic_cast<Interface2&>(one);
two.Name();
return 0;
}
And here's a rewrite with CRTP that might be what you want (or not):
template<class Derived>
struct RealClass1 : Interface1 {
#define self (*static_cast<Derived*>(this))
virtual void Name() {
printf("Interface1 for %s\n", self.name.c_str());
}
#undef self
};
template<class Derived>
struct RealClass2 : Interface2 {
#define self (*static_cast<Derived*>(this))
virtual void Name() {
printf("Interface2 for %s\n", self.name.c_str());
}
#undef self
};
struct RealClass : RealClass1<RealClass>, RealClass2<RealClass> {
std::string name;
RealClass() : name("real code would have members you need to access") {}
};
But note that here you cannot call Name on a RealClass now (with virtual dispatch, e.g. rc.Name()), you must first select a base. The self macro is an easy way to clean up CRTP casts (usually member access is much more common in the CRTP base), but it can be improved. There's a brief discussion of virtual dispatch in one of my other answers, but surely a better one around if someone has a link.
I've had to do something like this in the past, though in my case I needed to inherit from one interface twice and be able to differentiate between calls made on each of them, I used a template shim to help me...
Something like this:
template<class id>
class InterfaceHelper : public MyInterface
{
public :
virtual void Name()
{
Name(id);
}
virtual void Name(
const size_t id) = 0;
}
You then derive from InterfaceHelper twice rather than from MyInterface twice and you specify a different id for each base class. You can then hand out two interfaces independently by casting to the correct InterfaceHelper.
You could do something slightly more complex;
class InterfaceHelperBase
{
public :
virtual void Name(
const size_t id) = 0;
}
class InterfaceHelper1 : public MyInterface, protected InterfaceHelperBase
{
public :
using InterfaceHelperBase::Name;
virtual void Name()
{
Name(1);
}
}
class InterfaceHelper2 : public MyInterface, protected InterfaceHelperBase
{
public :
using InterfaceHelperBase::Name;
virtual void Name()
{
Name(2);
}
}
class MyClass : public InterfaceHelper1, public InterfaceHelper2
{
public :
virtual void Name(
const size_t id)
{
if (id == 1)
{
printf("Interface 1 OK?");
}
else if (id == 2)
{
printf("Interface 2 OK?");
}
}
}
Note that the above hasn't seen a compiler...
class BaseX
{
public:
virtual void fun()
{
cout << "BaseX::fun\n";
}
};
class BaseY
{
public:
virtual void fun()
{
cout << "BaseY::fun\n";
}
};
class DerivedX : protected BaseX
{
public:
virtual void funX()
{
BaseX::fun();
}
};
class DerivedY : protected BaseY
{
public:
virtual void funY()
{
BaseY::fun();
}
};
class DerivedXY : public DerivedX, public DerivedY
{
};
There are two other related questions asking nearly (but not completely) identical things:
Picking from inherited shared method names. If you want to have rc.name() call ic1->name() or ic2->name().
Overriding shared method names from (templated) base classes. This has simpler syntax and less code that your accepted solution, but does not allow for access to the functions from the derived class. More or less, unless you need to be able to call name_i1() from an rc, you don't need to use things like InterfaceHelper.