member function as callback - callback

I would like to pass a member function of an instantiated object to another function. Example code is below. I am open for any strategy that works, including calling functional() from another function inside memberfuncpointertestclass using something like lambda or std::bind. Please note that I did not understand most of the threads I found with google about lambda or std::bind, so please, if possible, keep it simple. Also note that my cluster does not have C++ 11 and I would like to keep functional() as simple as it is. Thank you!
int functional( int (*testmem)(int arg) )
{
int a = 4;
int b = testmem(a);
return b;
}
class memberfuncpointertestclass
{
public:
int parm;
int member( int arg )
{
return(arg + parm);
}
};
void funcpointertest()
{
memberfuncpointertestclass a;
a.parm = 3;
int (*testf)(int) = &a.member;
std::cout << functional(testf);
}
int main()
{
funcpointertest();
return 0;
}

You cannot invoke a method on an object without an instance to refer to. So, you need to pass in both the instance as well as the method you want to invoke.
Try changing functional to:
template <typename T, typename M>
int functional(T *obj, M method)
{
int a = 4;
int b = (obj->*(method))(a);
return b;
}
And your funcpointertest to:
void funcpointertest()
{
memberfuncpointertestclass a;
a.parm = 3;
std::cout << functional(&a, &memberfuncpointertestclass::member);
}

This is a job for std::function, a polymorphic function wrapper. Pass to functional(...) such a function object:
#include <functional>
typedef std::tr1::function<int(int)> CallbackFunction;
int functional(CallbackFunction testmem)
{
int a = 4;
int b = testmem(a);
return b;
}
then use std::bind to create a function object of the same type that wraps memberfuncpointertestclass::method() of instance a:
void funcpointertest()
{
memberfuncpointertestclass a;
a.parm = 3;
CallbackFunction testf = std::bind(&memberfuncpointertestclass::member, &a, std::placeholders::_1);
std::cout << functional(testf);
}
Check this item for more details.

Related

Why does vscode tell constructor defined outside class is inaccesible?

I have defined a constructor and then tried initializing an object but vscode tells me that the constructor is inaccessible. I don't understand what the problem is
this is my code
using namespace std;
#include<iostream>
class player{
// attributes
int xp{0};
string name;
int health{0};
float avg_score{0};
int tot{0};
int c{0};
// methods
void add_score(int score){
tot += score;
c++;
};
void display_avg_score(){
avg_score = tot/c;
cout << avg_score << endl;
};
void player_is_perfect(){
if((xp > 5) && (avg_score > 23)){
cout << "Perfect"<< endl;
}
};
// defining a constructor
player(int exp,float avg);
};
player::player(int exp,float avg){
xp = exp;
avg_score = avg;
};
int main(){
player frank{23,45.6};
};
As Raymond specified, classes have default access specifier "private". Anything you want to access outside the class should be preceded by the "public" statement like so
class player{
// attributes
int xp{0};
string name;
int health{0};
float avg_score{0};
int tot{0};
int c{0};
public:
// methods
void add_score(int score){
tot += score;
c++;
}
// rest of class
};

Classes in class in c++

I have this block of code below, and I cant find out what that class ContractB : public: ContractA means?
#include
using namespace std;
class ContractA
{
unsigned int ether = 0;
public:
ContractA(unsigned int e) :ether(e) {}
auto sendEther() { return ether; }
};
class ContractB : public ContractA
{
unsigned int wei = 1;
public:
ContractB(unsigned int w) :wei(w) {}
auto sendWei() { return wei; }
};
int main()
{
ContractB b(0);
cout << b.sendEther() << " " << b.sendWei();
return 0;
}
It represents inheritance. 'public' is the access specifier that limits the most accessible level for the members inherited from the base class (ContractA).
You can read more about it here.

How to define the operator= in a class to make a variable in it to be assigned to an outside variable

I have example code and classs:
class a{
int x;
a(){
this->x = 335; /* example number*/
}
public:
void operator=(int);
};
void a::operator=(int source){
this->x = source;
}
main(){
int i = 100;
a example_class;
example_class = i; //works fine!
i = example_class; /*this is what I want to do.*/
}
the problem with this hole thing is that I can't
make the operator= be a friend function
therefore the command: "i = example_class"
can't be done because I can't create a function in //the the int class like I normally would with my own classes.
Finally:
How can I complete the command:
"i = example_class" when the
operator= can't have more than 1
parameter?
notes:
I know the code doesn't do anything.
And is only an example. The point
Is what actually matters.
Also, I need to make it clear that I
cannot create any functions in the
Target class(in this case int). Only in
the source class(in this case a).
I also want to make clear that I know
that it's impossible to declare the
operator= as a friend function.
I know that I could just create a function
to get a reference to int x or make
int x public but I didn't want to do that
because the real code involves complex
functions for converting between types
so it's vary important to me to be able
to write: "i = example_class;".
Thanks,
Ronen.
Working example.
#include <iostream>
class a {
int x = 355;
public:
void operator=(int);
operator int();
};
void a::operator=(int source){
x = source;
}
a::operator int() {
return x;
}
int main(int, char**) {
int i = 100;
a example_class;
example_class = i;
int j = example_class;
std::cout << j << std::endl;
}

Want to reset integers using virtual class function

The function I want works within the class butt won't apply to main. Must maintain the initial (Entity *entity = new Nummchange(flarb);)
#include <iostream>
using namespace std;
class Entity
{
public:
Entity(){}
~Entity(){}
virtual int reset(int NUMM) = NULL;
protected:
private:
};
class Nummchange : public Entity
{
public:
Nummchange(int NUMM);
~Nummchange();
int reset(int NUMM);
protected:
private:
int numm;
};
Nummchange::Nummchange(int NUMM)
{
}
Nummchange::~Nummchange()
{
}
int Nummchange::reset(int NUMM)
{
numm = 50;
NUMM = numm;
std::cout << "\nnumm+++++++"<< numm << "\n" << std::endl;
return numm;
}
int main()
{
int flarb = 50;
Entity *entity = new Nummchange(flarb);
while (flarb >= 0)
{
flarb--;
cout << flarb;
if(flarb == 0)
{
entity->reset(flarb);
std::cout << "flarb+++++++"<< flarb << "\n" << std::endl;
}
}
system("pause");
return 0;
}
Success is if the while loop continues perpetually.
int reset(int NUMM); method should take reference of integer type as below.
int reset(int &NUMM);
Make sure that you change the parameter to be reference of integer in all the three places of the method use in the program.

Fibonacci Sequence error

I am coding a Fibonacci sequence in Eclipse and this is my code-
public class FibonacciAlgorithm {
private int a = 0;
private int b = 1;
public FibonacciAlgorithm() {
}
public int increment() {
int temp = b;
b = a + b;
a = temp;
return value;
}
public int getValue() {
return b;
}
}
It is showing an error in the return value; line saying value cannot be resolved to a variable. I don't see any other errors.
Where is value defined? You return something that was not defined anywhere.
You don't have a "value" defined, this is your error. I don't remember the thing exactly, but I think you don't need a and b, I found this in my code archive, hope it helps.
public class Fibonacci
{
public static long fibo(int n)
{
if (n <= 1) return n;
else return fibo(n - 1) + fibo(n - 2);
}
public static void main() {
int count = 5; // change accordingly, bind to input etc.
int N = Integer.parseInt(count);
for (int i = 1; i <= N; i++)
System.out.println(i + ": " + fibo(i));
}
}
In case you want to stay with your own code, try returning "b" as value.
Your method is returning an int variable so you would have to define and return value as an int
I am not sure what you trying to do.
If you have "getValue" method I think "increment" method should be void.
When you want current Fibonacci value use "getValue" method.
public class FibonacciAlgorithm {
private int a = 0;
private int b = 1;
public FibonacciAlgorithm() {
}
public void increment() {
int temp = b;
b = a + b;
a = temp;
}
public int getValue() {
return b;
}