Derived method in not called in base class - c++

I don't know how to put a right title. sorry by my problem is very hard with me.
I have a class myCal.h:
class myCal
{
public:
myCal();
int add(int a, int b);
int sub(int a, int b);
int expresstion(int a, int b, int c);
};
and myCal.cpp:
myCal::myCal()
{
}
int myCal::add(int a, int b)
{
return a+b;
}
int myCal::sub(int a, int b)
{
return a-b;
}
int myCal::expresstion(int a, int b, int c)
{
return add(sub(a, b), c);
}
in main.cpp, i have class mockcal like this:
class mockcal : public myCal
{
public:
int sub(int a, int b)
{
return 100;
}
int expresstion(int a, int b, int c)
{
return myCal::expresstion(a,b,c);
}
};
if I run myCal.expresstion(3,2,1), the return value is 2, that's OK,
but when I run mockCal.expresstion(3,2,1), the return values still is 2, I want it return 101.
please help me to do this, but do not change anything in mockCal::expresstion.
Thanks so much.

You need to make the method int sub(int a, int b) virtual in the base class ( myCal class in your code), if you want to override it in the mockcal class
class myCal
{
public:
//...
virtual int sub(int a, int b);
//..
};

Related

Mocking a non-virtual function using Google Mock?

I am trying to mock the function sub so that I can test the function add.I am using non-virtual function,
//Non_virtual function
class baseclass {
public:
int add(int a, int b) {
return (a + sub(a, b));
}
int sub(int c, int d) {
return (c - d);
}
};
class mockclass {
public:
MOCK_METHOD2(sub, int(int a, int b));
};
TEST(sample_test, testmain) {
mockclass mo;
int c = 12;
int d = 4;
EXPECT_CALL(mo, sub(c, d))
.WillOnce(testing::Return(8));
EXPECT_EQ(mo.add(c, d), 20);
}
I don't know how to make the relationship between the add and sub and don't know where I was making mistake.
I can do it with virtual function but I want to do it in non-virtual function.
Thanks in advance
Possible way without virtual:
struct MySub
{
int sub(int c, int d) const { return c - d; }
};
template <typename Sub>
class baseclassT : public Sub
{
public:
int add(int a, int b) {
return (a + this->sub(a, b));
}
};
using baseclass = baseclassT<MySub>; // For prod
And then, for test:
class MockSub {
public:
MOCK_METHOD2(sub, int(int a, int b));
};
TEST(sample_test, testmain)
{
baseclassT<MockSub> mo;
int c = 12;
int d = 4;
EXPECT_CALL(mo, sub(c, d)).WillOnce(testing::Return(8));
EXPECT_EQ(mo.add(c, d), 20);
}

How to properly pass member function as a parameter

How do I properly pass member function as a parameter?
MyCode:
#include <iostream>
using namespace std;
class Test
{
public:
int add(int a, int b)
{
return a + b;
}
int sub(int a, int b)
{
return a - b;
}
typedef int (*funcPtr)(int a, int b);
int myFunc(funcPtr func, int a, int b)
{
return func(a, b);
}
void setup()
{
cout << myFunc(&Test::add, 5, 3) << endl;
cout << myFunc(&Test::sub, 5, 3) << endl;
}
};
int main()
{
Test test;
test.setup();
}
Result:
Error: Cannot initialize a parameter of type 'Test::funcPtr' (aka 'int
()(int, int)') with an rvalue of type 'int (Test::)(int, int)'
Expected Result:
8
2
Your methods should be "regular" functions. add static to them to allow to use them with function pointers:
class Test
{
public:
static int add(int a, int b)
{
return a + b;
}
static int sub(int a, int b)
{
return a - b;
}
// ...
};
If you really pointer on method, you should replace int (*funcPtr)(int a, int b) by int (Test::*funcPtr)(int a, int b) and use something like that instead:
class Test
{
public:
int add(int a, int b)
{
return a + b;
}
int sub(int a, int b)
{
return a - b;
}
typedef int (Test::*funcPtr)(int a, int b);
int myFunc(funcPtr func, int a, int b)
{
return (this->*func)(a, b);
}
void setup()
{
cout << myFunc(&Test::add, 5, 3) << endl;
cout << myFunc(&Test::sub, 5, 3) << endl;
}
};
You should read about std:: function and std::bind. The first thing will allow you to store a function pointer with multiple form (Functor, lamda, binded), and the second will allow you to bind parameters to your function call (In your case, you want to bind the instance of the class that is needed to call your function).
std:: function<int(int, int)> func = std::bind(&Class::Method, instancePtr, std::placeholders::_1, std:: placeholders::_2);
int result = func(a, b);
However, in your context, your methods should be marked as static (They are not using any non-static member of your class), but the example and the explanation I provided answer to your base question
Firstly, based on your question the best solution here will be without using the pointer instead declare your methods as static and call them directly as given below.
That solution will generate the right results without using the complexity of pointers.
Simple is better if you do not need to use pointers it is better to not use them. code will be more readable as well.
Following code works i tested it:
#include <iostream>
using namespace std;
class Test
{
public:
static int add(int a, int b)
{
return a + b;
}
static int sub(int a, int b)
{
return a - b;
}
void setup()
{
cout << add( 5, 3) << endl;
cout << sub(5, 3) << endl;
}
};
int main()
{
Test test;
test.setup();
}

Fill map in Command pattern

#include <map>
class ICommand
{
public:
virtual double execute(double, double);
~ICommand();
};
class Add: public ICommand
{
public:
double execute(double a, double b) override
{
return a + b;
}
double operator()(double a, double b){
return a + b;
}
};
class Sub : public ICommand
{
public:
double execute(double a, double b) override
{
return a - b;
}
double operator()(double a, double b) {
return a - b;
}
};
class Mul : public ICommand
{
public:
double execute(double a, double b) override
{
return a * b;
}
double operator()(double a, double b) {
return a * b;
}
};
class Div : public ICommand
{
public:
double execute(double a, double b) override
{
return a / b;
}
double operator()(double a, double b) {
return a / b;
}
};
class RequestHundler
{
std::map<int, ICommand*> commands;
Add* add;
Sub* sub;
Mul* mul;
Div* div;
public:
RequestHundler()
{
commands[1] = add;
commands[2] = sub;
commands[3] = mul;
commands[4] = div;
}
double HandleRequest(int action, double a, double b)
{
ICommand* command = commands[action];
return command->execute(a, b);
}
};
int main(double argc, char* argv[])
{
RequestHundler* handler = new RequestHundler();
double result = handler->HandleRequest(2, 4, 6);
return 0;
}
I have access violation in command->execute(a, b);
, because map contains only null pointer, after filling. What is right way to store and filling map?
I think I should use factory for creating classes, but even in this case I must to fill map, and I not very want to use global variable for saving map. Maybe any good idea about this code?

Using nested class in head class constructor

I want to make something that I pasted in code.
I want to use Nested class in Head class, look on code below.
What should I do? I was trying to use a nested construktor in initialization list but still not work. Any ideas?
class Head{
private:
int x;
public:
Head(int x, const Nested& n){
this->x=x;
}
class Nested{
private:
int a;
int b;
public:
Nested(int a, int b){
this->a=a;
this->b=b;
}
}
}
You mean you have a compile error? You should define Nested before its use, as below:
class Head{
private:
int x;
public:
class Nested {
private:
int a;
int b;
public:
Nested(int a, int b){
this->a=a;
this->b=b;
}
};
Head(int x, const Nested& n){
this->x=x;
}
};
int main()
{
Head::Nested n(0, 0);
Head h(0, n);
}

How to best pass methods into methods of the same class

I have this C++ class that one big complicated method compute that I would like to feed with a "compute kernel", a method of the same class. I figure I would do something along the lines of
class test {
int classVar_ = 42;
int compute_add(int a, int b)
{
compute(int a, int b, this->add_())
}
int compute_mult(int a, int b)
{
compute(int a, int b, this->mult_())
}
int compute_(int a, int b, "pass in add or multiply as f()")
{
int c=0;
// Some complex loops {
c += f(a,b)
// }
return c;
}
int add_(int a, int b){a+b+classVar_;}
int multiply_(int a, int b){a*b+classVar_;}
...
}
but I'm not sure how I would pass in add or multiply.
An alternative to this approach would be to pass in an ENUM of some sort to specify add() or multiply(), but I wanted to avoid a switch or if inside the loops.
What's best practice here?
As you suspected, passing a member function pointer is acceptable practice.
If you need to know the syntax, it is:
int compute_(int a, int b, int (test::*f)(int,int))
{
int c=0;
// Some complex loops {
c += (this->*f)(a,b)
// }
return c;
}
Representing member functions using integers, and switching, introduces programmer overhead to keep things up to date when the list of available operations changes. So you don't want that unless there's some important reason in a particular case.
One alternative is to make compute even more general -- instead of taking a member function, write a function template that takes any callable type:
template <typename BinaryFunction>
int compute_(int a, int b, BinaryFunction f) {
// body as before but `f(a,b)` instead of `(this->*f)(a,b)`
}
This more general template is great if someone wants to use it with some operator of their own invention, that isn't a member function of test. It's more difficult to use in the case of the member function, though, because someone needs to capture this. There are a few ways to do that -- a C++11 lambda, boost::bind, or writing out a functor longhand. For example:
template <typename BinaryFunction>
int compute_(int a, int b, BinaryFunction f) {
// body as before with `f(a,b)`
}
int compute_(int a, int b, int (test::*f)(int,int))
{
return compute_(a, b, bind_this(f, this));
}
Defining bind_this is a bit of a pain: it's like std::bind1st except that we'd like to work with a 3-arg functor whereas bind1st only takes a binary functor. boost::bind, and std::bind in C++11, are more flexible, and will handle the extra arguments. The following will do for this case, but doesn't work in general to bind 2-arg member functions:
struct bind_this {
int (test::*f)(int,int);
test *t;
int operator(int a, int b) const {
return (t->*f)(a,b);
}
bind_this(int (test::*f)(int,int), test *t) : f(f), t(t) {}
};
In C++11 you can just use a lambda:
int compute_(int a, int b, int (test::*f)(int,int))
{
return compute_(a, b, [=](int c, int d){ return (this->*f)(c,d) });
}
Use pointers to functions.
int compute(int a, int b, int (test::*f) (int, int) )
{
int c=0;
// Some complex loops {
c += (this->*f)(a,b)
// }
return c;
}
You have two alternatives :
using pointer to member function
using lambda functions
Example using pointer to member function :
#include <iostream>
class D
{
public:
D(int v ) : classVar_(v){}
int add_(int a, int b){return (a+b+classVar_);}
int multiply_(int a, int b){return (a*b+classVar_);}
private:
int classVar_;
};
class test {
public:
int compute_(int a, int b, D &d, int (D::*f)(int a, int b))
{
int c=0;
// Some complex loops {
c += (d.*f)(a,b);
// }
return c;
}
};
int main()
{
test test;
D d(1);
std::cout<<"add : " << test.compute_( 5, 4, d, &D::add_ ) << std::endl;
std::cout<<"add : " << test.compute_( 5, 4, d, &D::multiply_ ) << std::endl;
}
Example using lambda :
#include <iostream>
#include <functional>
class D
{
public:
D(int v ) : classVar_(v){}
int add_(int a, int b){return (a+b+classVar_);}
int multiply_(int a, int b){return (a*b+classVar_);}
private:
int classVar_;
};
class test {
public:
int compute_(int a, int b, std::function< int(int,int) > f)
{
int c=0;
// Some complex loops {
c += f(a,b);
// }
return c;
}
};
int main()
{
test test;
D d(1);
std::cout<<"add : " << test.compute_( 5, 4, [&d](int a, int b){ return d.add_(a,b); } ) << std::endl;
std::cout<<"add : " << test.compute_( 5, 4, [&d](int a, int b){ return d.multiply_(a,b); } ) << std::endl;
}