#include <iostream>
using namespace std;
class B
{
public:
int getMsg(int i)
{
return i + 1;
}
};
class A
{
B b;
public:
void run()
{
taunt(b.getMsg);
}
void taunt(int (*msg)(int))
{
cout << (*msg)(1) << endl;
}
};
int main()
{
A a;
a.run();
}
The above code has a class B inside a class A, and class A has a method taunt that takes a function as an argument. class B's getMsg is passed into taunt...The above code generated the following error message: "error: no matching function for call to 'A::taunt()'"
What's causing the error message in the above code? Am I missing something?
Update:
#include <iostream>
using namespace std;
class B
{
public:
int getMsg(int i)
{
return i + 1;
}
};
class A
{
B b;
public:
void run()
{
taunt(b.getMsg);
}
void taunt(int (B::*msg)(int))
{
cout << (*msg)(1) << endl;
}
};
int main()
{
A a;
a.run();
}
t.cpp: In member function 'void A::run()':
Line 19: error: no matching function for call to 'A::taunt()'
compilation terminated due to -Wfatal-errors.
I'm still getting the same error after changing (*msg)(int) to (B::*msg)(int)
b.getMsg is not the correct way to form a pointer to member, you need &B::getMsg.
(*msg)(1) is not the correct way to call a function through a pointer to member you need to specify an object to call the function on, e.g. (using a temporary) (B().*msg)(1).
The right way to do such things in OOP is to use interfaces so all you need to do is to define an interface and implement it in B class after that pass the pointer of instance which implements this interface to your method in class A.
class IB{
public:
virtual void doSomething()=0;
};
class B: public IB{
public:
virtual void doSomething(){...}
};
class A{
public:
void doSomethingWithB(IB* b){b->doSomething();}
};
This works in VS 2010. The output is the same on all lines:
#include <iostream>
#include <memory>
#include <functional>
using namespace std;
using namespace std::placeholders;
class A
{
public:
int foo(int a, float b)
{
return int(a*b);
}
};
int main(int argc, char* argv[])
{
A temp;
int x = 5;
float y = 3.5;
auto a = std::mem_fn(&A::foo);
cout << a(&temp, x, y) << endl;
auto b = std::bind(a, &temp, x, y);
cout << b() << endl;
auto c = std::bind(std::mem_fn(&A::foo), &temp, _1, y);
cout << c(5) << endl;
}
Basically, you use std::mem_fn to get your callable object for the member function, and then std::bind if you want to bind additional parameters, including the object pointer itself. I'm pretty sure there's a way to use std::ref to encapsulate a reference to the object too if you'd prefer that. I also included the _1 forwarding marker just for another way to specify some parameters in the bind, but not others. You could even specify everything BUT the class instance if you wanted the same parameters to everything but have it work on different objects. Up to you.
If you'd rather use boost::bind it recognizes member functions and you can just put it all on one line a bit to be a bit shorter: auto e = boost::bind(&A::foo, &temp, x, y) but obviously it's not much more to use completely std C++11 calls either.
Related
I am typing the following code and I am getting the following error at line-1
[Error] no matching function for call to 'int_adder::add()
#include <iostream>
using namespace std;
class adder{
public:
void add(){ cout <<"adder::add() "; }
};
class int_adder : public adder{
public:
int add(int a, int b){
return (a + b);
}
};
int main(){
int_adder ia;
ia.add(); //LINE-1
cout << ia.add(10, 20); //LINE-2
return 0;
}
As pointed by others in the comment, I have corrected it:-
#include <iostream>
using namespace std;
class adder{
public:
void add(){ cout <<"adder::add() "; }
};
class int_adder : public adder{
public:
int add(int a, int b){
return (a + b);
}
};
int main(){
int_adder ia;
ia.adder::add(); //LINE-1
cout << ia.add(10, 20); //LINE-2
return 0;
}
The statement adder::add() will overide the function add() present in int_adder.
Can't fing exact dupe, but you can make overloads from base class visible by using using directive, example:
#include <iostream>
using namespace std;
class adder{
public:
void add(){ cout <<"adder::add() "; }
};
class int_adder : public adder{
public:
using adder::add; // expose base class overload as our own
int add(int a, int b){
return (a + b);
}
};
int main(){
int_adder ia;
ia.add(); //LINE-1
ia.adder::add(); // explicit name also works
cout << ia.add(10, 20); //LINE-2
return 0;
}
As the other answer mentions using base class name scope also works. It all depends on your needs and class design.
Basically defining an overload in a derived class prevents implicit method look up from matching base class overloads, so you have to be explicit about it in one way or another.
You have totally two different versions of add in the first place. You are not overriding, you are overloading. You are just providing a new add function that has nothing to do with the other add function of the parent.
So first of all, do you want to override or overload?
Overriding the parent add would like the following:
#include <iostream>
using namespace std;
class adder{
public:
void add(){ cout <<"adder::add() "; }
};
class int_adder : public adder{
public:
int add() override {cout <<"int_adder ::add() ";};
int add(int a, int b){
return (a + b);
}
};
int main(){
int_adder ia;
ia.adder::add(); //LINE-1 <- would work displays adder::add()'s message
cout << ia.add(10, 20); //LINE-2
adder ia = int_adder{}; // now this is interesting
ia.add(); // would work displays adder::add()'s message - cause you did not ask for virtuality
return 0;
}
I'm learning the concept of passing a function as a parameter.
First I've tried pass a "free function?" (function that not belong to any class or struct) to another free function using this pointer void(*Func)(int) and it worked.
Second, a free function to a function belong to a struct using the same pointer, also worked.
But when I tried to pass a function in a struct to another function in a different struct with that same pointer, it prompted error.
Here's my code:
#include <iostream>
#include <stdio.h>
#include <windows.h>
#include <conio.h>
using namespace std;
struct A {
void Func_A (void (*Func)(int)) {
(*Func)(5);
}
};
struct B {
void Func_B (int a) {
cout<<a;
}
};
int main () {
A a;
B b;
a.Func_A(b.Func_B);
char key = getch();
return 0;
}
Here the error prompt:
[Error] no matching function for call to 'A::Func_A(<unresolved overloaded function type>)'
To pass a non-static member function around, the syntax is a little different. Here is your original code, reworked to show this:
#include <iostream>
struct B {
void Func_B (int a) {
std::cout << a;
}
};
struct A {
void Func_A (void (B::*Func)(int), B &b) {
(b.*Func) (5);
}
};
int main () {
A a;
B b;
a.Func_A (&B::Func_B, b);
return 0;
}
Note the different function signature for Func_A and the fact that you have to pass an instance of class B when you call it.
Live demo
It's a shame you can't use C++11. std::function makes this a lot simpler and more generalised.
Consider this example:
#include <iostream>
using namespace std;
struct A {
void Func_A (void (*Func)(int)) {
(*Func)(5);
}
};
struct B {
int x;
void Func_B (int a) {
cout << a << " " << x;
}
};
int main () {
A a;
B b1;
b1.x = 1;
B b2;
b2.x = 2;
a.Func_A(b1.Func_B);
return 0;
}
In that example, Func_B uses both the input a and the data member x, so it is clear that the result of a call to Func_B will be different depending on the object, if it is b1 or b2 that is calling it.
You might think that taking the function pointer "b1.Func_B" would clarify that you mean the function associated with the b1 object, but that does not work because the member functions do not exist separately for each instance. The function Func_B only exists once in memory, so it is not possible to have separate function pointers for "b1.Func_B" and "b2.Func_B". So, it cannot work.
The g++ 8.2.0 compiler gives the following error message for the a.Func_A(b1.Func_B); line in the code:
error: invalid use of non-static member function ‘void B::Func_B(int)’
hinting that it would be OK to do such a thing for a static member function. That makes sense, because a static member function cannot make use of the data members of any instance, so it is more like a "free function", not dependent on any instance.
I need help with passing a function pointer on C++. I can't linkage one function for a class to other function. I will explain. Anyway I will put a code resume of my program, it is much larger than the code expose here but for more easier I put only the part I need to it works fine.
I have one class (MainSystem) and inside I have an object pointer to the other class (ComCamera). The last class is a SocketServer, and I want when the socket received any data, it sends to the linkage function to MainSystem.
ComCamera is a resource Shared with more class and I need to associate the functions ComCamera::vRecvData to a MainSystem::vRecvData or other function of other class for the call when receive data and send de data to the function class associate.
Can Anyone help to me?
EDDITED - SOLUTION BELOW
main.cpp
#include <iostream>
#include <thread>
#include <string>
#include <vector>
#include <cmath>
#include <string.h>
#include <stdio.h>
#include <exception>
#include <unistd.h>
using std::string;
class ComCamera {
public:
std::function<void(int, std::string)> vRecvData;
void vLinkRecvFunction(std::function<void(int, std::string)> vCallBack) {
this->vRecvData = vCallBack;
}
void vCallFromCamera() {
this->vRecvData(4, "Example");
};
};
class MainSystem {
private:
ComCamera *xComCamera;
public:
MainSystem(ComCamera *xComCamera) {
this->xComCamera = xComCamera;
this->xComCamera->vLinkRecvFunction([this](int iChannelNumber, std::string sData) {vRecvData(iChannelNumber, sData); });
}
void vRecvData(int iNumber, string sData) {
std::cout << "RECV Data From Camera(" + std::to_string(iNumber) + "): " << sData << std::endl;
};
};
int main(void) {
ComCamera xComCamera;
MainSystem xMainSystem(&xComCamera);
xComCamera.vCallFromCamera();
return 0;
}
Output will be:
MainSystem RECV Data From Camera(4): Example
You can have ComCamera::vRecvData be of type std::function<void(int, std::string)> and then have ComCamera::vLinkRecvFunction() be like this:
void ComCamera::vLinkRecvFunction(std::function<void(int, std::string)> callBack)
{
this->vRecvData = callBack;
}
and have MainSystem constructor be like this:
MainSystem::MainSystem(ComCamera *xComCamera)
{
using namespace std::placeholders;
this->xComCamera = xComCamera;
this->xComCamera->vLinkRecvFunction([this](int iNumber, std::string sData){vRecvData(number, sData);});
}
Still though the original question has way too much code to go through friend.
Here what you want :
#include<iostream>
using std::cout;
class A; //forward declare A
class B{
public:
void (A::*ptr)(int x); //Only declare the pointer because A is not yet defined.
};
class A{
public:
void increase_by(int x){
a+=x;
} // this function will be pointed by B's ptr
int a = 0; // assume some data in a;
B b; // creating B inside of A;
void analyze(int y){
(*this.*(b.ptr))(y);
} // Some function that analyzes the data of A or B; Here this just increments A::a through B's ptr
};
int main(){
A a; // creates A
cout<<a.a<<"\n"; // shows initial value of a
a.b.ptr = &A::increase_by; // defines the ptr that lies inside of b which inturns lies inside a
a.analyze(3); // calls the initialize method
(a.*(a.b.ptr))(3); // directly calls b.ptr to change a.a
cout<<a.a; // shows the value after analyzing
return 0;
}
Output will be :
0
6
I still don't get why would you do something like this. But maybe this is what you wanted as per your comments.
To know more read this wonderful PDF.
How can such a code work correctly when the IWindow pointer clearly has an address to a ISheet class which has no method Say?
#include <iostream>
using namespace std;
class IWindow
{
private:
int p;
double f;
public:
void Say() { cout << "Say in IWindow"; }
};
class ISheet
{
public:
void foo() { cout << "ISheet::foo"; }
};
int main()
{
ISheet *sh = new ISheet();
int ptr = (int)sh;
IWindow *w = (IWindow*)ptr;
w->Say();
sh->foo();
return 0;
}
When compiled in Visual Studio 2015 it runs and executes with no problems, but I was expecting to get an error on line w->Say(). How is this possible?
It works by the grace of the almighty Undefined Behavior. Your functions don't try to access any data members of the containing class, they just write something to std::cout, which anyone can do.
What you've effectively done is
#include <iostream>
void IWindow_Say(void*)
{
std::cout << "Say in IWindow";
}
int main()
{
IWindow_Say(0xdeadbeef); // good luck with that pointer
}
You never used the pointer (which became this in your original example) so no side-effects were observed.
I'm new to C++ and get a beginner's mistake:
myclass.cpp: In function ‘int main()’:
myclass.cpp: 14:16: error: ‘func’ was not declared in this scope
This is the code:
#include <iostream>
using namespace std;
class MyClass{
public:
int func(int);
};
int MyClass::func(int a){
return a*2;
}
int main(){
cout << func(3);
}
I hope you can help me.
int main(){
cout << func(3);
}
func is not a global function; it is a member function of the class. You need an instance of the class to access it.
For example:
int main()
{
MyClass obj;
std::cout<< obj.func(3);
}
func is a member function, so it must be invoked through an object. For example:
int main()
{
MyClass obj;
std::cout << obj.func(3); // 6
}
In your example, you treated it as a free function, so the compiler looked for a function with that name. Since it could not find it, it issued a compiler error.
func is a member function of MyClass. To call it, you need an object of MyClass type to invoke it on:
int main(){
MyClass m; // Create a MyClass object
cout << m.func(3);
}
Alternatively, you could make func a static member function, which means that it is not associated with any particular instance of the class. However, you would still need to qualify its name as belonging to the MyClass class:
class MyClass{
public:
static int func(int);
};
int MyClass::func(int a){
return a*2;
}
int main(){
cout << MyClass::func(3);
}