C++ pass a function in a class by reference - c++

I'm trying to pass a reference to a function in a class but am having trouble figuring out how to do it. So say I have a class test defined as such
#include <iostream>
class test {
public:
test () {};
~test () {};
void setA (int);
int getA (void);
private:
int a;
};
void test::setA (int A) { a = A; }
int test::getA (void) { return a; }
using namespace std;
int main ()
{
test T;
T.setA(5);
cout << "a = " << T.getA() << endl;
return 0;
}
That works fine but if I want to pass the values by reference
#include <iostream>
class test {
public:
test () {};
~test () {};
void setA (int);
int & getA (void);
private:
int a;
};
void test::setA (int & A) { a = A; }
int & test::getA (void) { return a; }
using namespace std;
int main ()
{
test T;
T.setA(5);
cout << "a = " << T.getA() << endl;
return 0;
}
I cannot figure out how to configure setA to pass by reference.

There are two issues with the code. First, the definition of setA does not match the declaration. You must make the declaration take in a reference as a parameter.
Change this:
void setA (int);
To this:
void setA (int&);
The second issue is that you are trying to pass an r-value (5) as a reference. You must pass in an l-value. You can do that by creating an int first and then passing that by reference:
int i = 5;
T.setA(i);
Full example:
#include <iostream>
class test {
public:
test () {};
~test () {};
void setA (int&);
int & getA (void);
private:
int a;
};
void test::setA (int & A) { a = A; }
int & test::getA (void) { return a; }
using namespace std;
int main ()
{
test T;
int i = 5;
T.setA(i);
cout << "a = " << T.getA() << endl;
return 0;
}
When you pass something by reference to a function in C++, the function does not keep the parameter in memory automatically. Thus, you have to declare it before so that it stays in memory throughout the entire function.
The 5 you tried to pass as a reference would go out of scope and get destroyed as soon as the function starts. The declared i variable is instead destroyed at the end of the main function.

The reason is because in order to pass by reference, you must have an lvalue, which is a fancy way of saying something that persists beyond a single use.
If you created an int variable, you would be able to pass it in by reference. In the code above, you attempted to pass in a raw integer value (5), which fails, since the compiler is expecting a reference to an int, not a raw integer value.
The following code would work:
int main ()
{
test T;
int myVariable = 4; // Need an actual variable to pass by reference.
T.setA(myVariable);
cout << "a = " << T.getA() << endl;
return 0;
}
However, if you want your function to take raw integer values like you showed in your second example, you must have a function definition like your first example, where all the function takes is an integer. Hope this helps!

Maybe you could try this:
#include <iostream>
class test {
public:
test() {};
~test() {};
void setA(int&&); // requires at least C++11
void setA(int&);
int & getA(void);
private:
int a;
};
void test::setA(int && A) { a = A; }
void test::setA(int&A) { a = A; }
int & test::getA(void) { return a; }
using namespace std;
int main()
{
test T;
int i = 5;
T.setA(i);
cout << "a = " << T.getA() << endl;
T.setA(8);
cout << "a = " << T.getA() << endl;
return 0;
}
In the example, int& passes a l-value while int&& passes a r-value as a reference.

Related

C++: array of pointers to functions

Say we have 2 functions
foo() { cout << "Hello"; }
foo2() { cout << " wolrd!"; }
how can i create an array of pointers (say a, b), with a pointing to foo() and b to foo2() ?
my goal is to store these pointers in an array A, then loop over A to execute these functions.
You can use typed function pointers as follows:
using FunPtrType = void(*)();
FunPtrType arr[]{&foo, &foo2};
// or
std::array<FunPtrType, 2> arr2{&foo, &foo2};
// ... do something with the array of free function pointers
// example
for(auto fun: arr2)
fun();
There is a simple implementation:
#include <iostream>
#include <vector>
using namespace std;
// Defining test functions
void a(){cout<<"Function A"<<endl;}
void b(){cout<<"Function B"<<endl;}
int main()
{
/*Declaring a vector of functions
Which return void and takes no arguments.
*/
vector<void(*)()> fonc;
//Adding my functions in my vector
fonc.push_back(a);
fonc.push_back(b);
//Calling with a loop.
for(int i=0; i<2; i++){
fonc[i]();
}
return 0;
}
There's no need for typedefs these days, just use auto.
#include <iostream>
void foo1() { std::cout << "Hello"; }
void foo2() { std::cout << " world!"; }
auto foos = { &foo1, &foo2 };
int main() { for (auto foo : foos) foo(); }
There are two equivalent ways to do what you want:
Method 1
#include <iostream>
void foo()
{
std::cout << "Hello";
}
void foo2()
{
std::cout << " wolrd!";
}
int main()
{
void (*a)() = foo;// a is a pointer to a function that takes no parameter and also does not return anything
void (*b)() = foo2;// b is a pointer to a function that takes no parameter and also does not return anything
//create array(of size 2) that can hold pointers to functions that does not return anything and also does not take any parameter
void (*arr[2])() = { a, b};
arr[0](); // calls foo
arr[1](); //calls foo1
return 0;
}
Method 1 can be executed here.
Method 2
#include <iostream>
void foo()
{
std::cout << "Hello";
}
void foo2()
{
std::cout << " wolrd!";
}
int main()
{
//create array(of size 2) that can hold pointers to functions that does not return anything
void (*arr[2])() = { foo, foo2};
arr[0](); // calls foo
arr[1](); //calls foo1
return 0;
}
Method 2 can be executed here.

How to initialize a reference member variable inside a member function & access it inside other member functions - C++

The usual method one'd use for normal variables (declaring outside the member functions & initializing inside a member function) doesn't work, as reference variables need to be initialized & declared in same line.
#include <iostream>
using namespace std;
class abc {
public:
int& var;
void fun1 (int& temp) {var=temp;}
void fun2 () {cout << abc::var << endl;}
abc() {}
};
int main() {
abc f;
int y=9;
f.fun1(y);
f.fun2();
return 0;
}
How to initialize a reference member variable inside a member function & access it inside other member functions - C++
Use a pointer.
#include <iostream>
using namespace std;
class abc {
public:
int* var;
void fun1 (int& temp) { var = &temp; }
void fun2 () { cout << *abc::var << endl; }
abc() {}
};
int main() {
abc f;
int y=9;
f.fun1(y);
f.fun2();
return 0;
}
I think this is the best you can do.
#include <iostream>
using namespace std;
class abc {
public:
int& var;
abc(int& temp) :
var(temp)
{}
void fun2 () {cout << abc::var << endl;}
};
int main() {
int y=9;
abc f(y);
f.fun2();
return 0;
}
A reference is a constant thing — it refers to the same integer for the entire lifespan of the object. That means you need to set it on construction.
int var; int& varref = abc::var;
This should work!

Use an external function as a method of a class

I'm trying to make this code work:
#include <iostream>
using namespace std;
int f(int x) {
return x+1;
}
class A {
public:
int g(int y);
};
int A::g(int y) = f;
int main() {
A test;
cout << test.g(3) << endl;
return 0;
}
It does not compile because of the line int A::g(int y) = f;.
What is the correct way to achieve that an external function can be used as a method?
You can use a pointer to function as a member of class A. Now assign function f to g member of A.
int f(int x) {
return x+1;
}
class A {
public:
int (*g)(int);
};
int main(){
A test;
test.g = f;
cout << test.g(10); // prints 11
}
You can accomplish the same by making your function a callable objects by implementing () operator. so you can have that as member of the class, and then it can normally be used as function on the class objects.
#include <iostream>
struct do_something{
int operator()(int num){
return num;
}
};
class test{
int sum;
public:
do_something fun;
};
int main(){
test obj;
std::cout << obj.fun(10);
}

How to read the following code for main? I do not know this

How to read the following code for main?
I do not know this
Code :
class one
{
public:
void operator()() const
{
f();
f1();
}
};
I want to call the operator To main?
void operator()() const defines a function call operator, which can be used as:
one ob;
ob(); // calls ob.operator()()
For another, more complete, example.
#include <iostream>
class Two
{
public:
int operator()(const char *str) const
{
std::cout << "operator() called with " << str << std::endl;
return 101;
}
};
int main()
{
Two two;
int n = two("'test'");
std::cout << "operator() returned " << n << std::endl;
}
Output:
operator() called with 'test'
operator() returned 101
You can create an instance of the class in the main function and call the function using that instance.
class one
{
public:
void operator()() const
{
f();
f1();
}
};
int main() {
one obj_one;
// calling the member function -> method
obj_one.operator()();
return 0;
}

How to call object's methods using a function pointer?

I'd like to call a few methods of classes 'A' and 'B' from the class 'Caller'. I need to use a function pointer because I want to call different methods.
My method gets called, but when I try to access a member variable from it, my program crashes ('program.exe has stopped working').
How come that happens?
#include <iostream>
using namespace std;
template <class T>
class Caller
{
typedef void (T::*myFunc)(int);
public:
Caller(T* obj, myFunc fp)
{
f = fp;
}
void invoke(int foobar)
{
(o->*f)(foobar);
}
private:
myFunc f;
T* o;
};
class A
{
public:
A() : n(0) {}
void foo(int bar)
{
cout << "A::foo called (bar = " << bar << ", n = " << n << ")" << endl; // the crash occurs here, and 'this' equals 0 at this point
}
void setNum(int num)
{
n = num;
}
private:
int n;
};
class B
{
public:
B() : n(0) {}
void fooo(int bar)
{
cout << "B::fooo called (bar = " << bar << ", n = " << n << ")" << endl; // same here if I call B::fooo first
}
void setNum(int num)
{
n = num;
}
private:
int n;
};
int main()
{
A myA;
B myB;
myA.setNum(128);
myB.setNum(256);
Caller<A> cA(&myA, &A::foo);
Caller<B> cB(&myB, &B::fooo);
cA.invoke(10);
cB.invoke(20);
return 0;
}
Thank you in advance.
EDIT : I use VS2017 and I can build my program without getting any compiler errors.
My method gets called, but when I try to access a member variable from it, my program crashes ...
Because you forgot to assign passed obj to o pointer in your Caller:
template <class T>
class Caller
{
typedef void (T::*myFunc)(int);
public:
Caller(T* obj, myFunc fp)
{
o = obj; // << == you need this!
f = fp;
}
void invoke(int foobar)
{
(o->*f)(foobar);
}
private:
myFunc f;
T* o;
};
Also, in general it's better to use member initializer lists:
Caller::Caller(T* obj, myFunc fp) : o(obj), f(fp)
{
}