I'm not sure if this has already been answered somewhere or if what I'm asking is feasible. I'm not so familiar with C++ and OOP in general so forgive me if I'm asking something too obvious, as my mind is a bit stuck right now. Anyway, what I want to deal with is:
I'm using a framework that handles some callbacks from an app. The API has a class for these events and the callback function as pure virtual function. For example:
class A {
public:
A(){};
~A(){};
virtual void myCallback(){} = 0
};
In my code I'm implementing this callback and I have something like:
class B : A {
public:
B(){
std::cout<<"I'm a ClassB object";
};
~B(){};
void myCallback(){
std::cout<<"Hello callback";
};
};
Now in my main suppose that I'm having something like that:
int main(){
int x=1;
B objB;
//Do some stuff for a while
return 1;
}
I can see upon instantiating the B object the "I'm a ClassB object" message and I can see upon firing the event the "Hello callback" message. So what I'm asking here is how I can get inside my callback the value of "x" coming from main ? Can I re-implement the callback inside the main somehow? Do you think that my approach on this is correct ? What I want is to implement pure virtual callback function inside my main by having an object of class B. Or even to somehow get the value of x inside the myCallback function. I'm not sure if I'm clear enough or if I messed anything up
If I understand the question, what you want is usually called a closure . You want myCallback
to know the value of x inside main. There are several ways of doing this, the most straightforward will look something like following:
class B : public A {
public:
B(int x) x(x) {
std::cout<<"I'm a ClassB object";
}
~B() = default;
void myCallback() {
std::cout << "Hello callback, x is " << x << "\n";
}
private:
int x;
};
int main() {
int x = 1;
B objB(x);
//Do some stuff for a while
return 0;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.