I want to pass an function as argument. I know you can pass a function pointer like the first test in my example, but is it possible to pass a hold function (not a pointer) like my second test?
#include <iostream>
using namespace std;
/* variable for function pointer */
void (*func)(int);
/* default output function */
void my_default(int x) {
cout << "x =" << "\t" << x << endl << endl;
}
/* entry */
int main() {
cout << "Test Programm\n\n";
/* 1. Test - default output function */
cout << "my_default\n";
func = &my_default; // WORK! OK!
func(5);
/* 2. Test - special output function 2 */
cout << "my_func2\n";
func = void my_func1(int x) {
cout << "x =" << " " << x << endl << endl;
}; // WON'T WORK! FAILED!
func(5);
return 0;
}
In C++ 11, you can pass a lambda:
func = [](int x) { cout << "x =" << " " << x << endl << endl; };
EDIT: lambdas can return values:
func = [](int x)->int{ cout << "x =" << " " << x << endl << endl; return x; };
With c++11, you can write such code in a lot simpler way:
Instead of writing function signature use auto
auto func = &my_default; // WORK! OK!
func(5);
you can also use std::function objects to pass them around:
template<typename T>
void callme(std::function<T> f) {
f(6);
}
std::function<decltype(my_default)> func1 = &my_default;
func(5);
callme(func1);
and also you can use lambdas:
/* 2. Test - special output function 2 */
cout << "my_func2\n";
auto fun = [](int x) {
cout << "x =" << " " << x << endl << endl;
};
fun(5);
Even with return value it work:
#include <iostream>
using namespace std;
/* variable for function pointer */
int (*func)(int);
/* default output function */
int my_default(int x) {
//cout << "x =" << "\t" << x << endl << endl;
return x;
}
/* entry */
int main() {
cout << "Test Programm\n\n";
/* 1. Test - default output function */
cout << "my_default\n";
func = &my_default; // WORK! OK!
cout << func(5) << endl << endl;
/* 2. Test - special output function 2 */
cout << "my_func2\n";
func = [](int x) {
//cout << "x =" << " " << x << endl << endl;
return x;
};
cout << func(5) << endl << endl;
return 0;
}
You can uses lamdas:
std::function<int(int)> func2 = [](int i) { return i+4; };
std::cout << "func2: " << func2(6) << '\n';
if the body consists of the single return statement, the return type
is the type of the returned expression (after rvalue-to-lvalue,
array-to-pointer, or function-to-pointer implicit conversion)
If you lamda constains not single return statamen you should specify return type
std::function<int(int)> func2 = [=](int i) ->int {
if (globalVar)
return i*4;
else
return 4;
};
std::cout << "func2: " << func2(6) << '\n';
Related
I've tried to understand the semantics of c++ temporary objects lifetime extension. I've tried to simulate simple situation and was a bit surprised.
Below I'm providing my code.
#include <iostream>
struct C
{
C(const int new_a) { a = new_a; };
int a = 0;
};
C return_num()
{
C num(20);
std::cout << "From func(): num = " << num.a << ", by adress: " << &num.a << std::endl;
return num;
}
void pass_num(const C& num)
{
std::cout << "From func(): num = " << num.a << ", by adress: " << &num.a << std::endl;
}
int main()
{
std::cout << "\nLifetime extention:" << std::endl;
{
const C& ext_num = return_num();
std::cout << "From main(): num = " << ext_num.a << ", by adress: " << &ext_num.a << std::endl;
}
std::cout << "\nPassing by reference:" << std::endl;
{
C num(20);
std::cout << "From main(): num = " << num.a << ", by adress: " << &num.a << std::endl;
pass_num(num);
}
}
Here is the main question: return_num() works curiously from my point of view, cause I expected that address of the variable, which I'm trying to output in main, would be the same as internally in return_num(). Could you please explain me why it is not?
For example in pass_num() output address matches the external address which I got in main.
Here is example output:
Lifetime extention:
From func(): num = 20, by adress: 0x7fff44fc8b4c
From main(): num = 20, by adress: 0x7fff44fc8b70
Passing by reference:
From main(): num = 20, by adress: 0x7fff44fc8b6c
From func(): num = 20, by adress: 0x7fff44fc8b6c
Move constructors typically "steal" the resources held by the argument (e.g. pointers to dynamically-allocated objects, file descriptors, TCP sockets, I/O streams, running threads, etc.) rather than make copies of them, and leave the argument in some valid but otherwise indeterminate state.
Please see Move Constructor
I changed the below in your code and I hope it is working as expected. I changed int a to int* a
#include <iostream>
class C
{
public:
int *a;
C( int new_a)
{
a = new int();
*a = new_a;
};
C(const C& rhs) { std::cout << "Copy " << std::endl; this->a = rhs.a; }
C(C&& rhs):a(std::move(rhs.a))
{
std::cout << "Move!!" <<"Address resource a " << &(*a) << ", Address of
resource rhs.a" << &(*rhs.a) << std::endl; rhs.a = nullptr;
std::cout << "Value of a:: " << *a << std::endl;
}
};
C return_num()
{
C num(20);
std::cout << "From return_num(): num = " << *num.a << ", Address of resource a :
"<< &(*num.a)<< std::endl;
return (std::move(num));
}
void pass_num(const C& num)
{
std::cout << "From pass_num(): num = " << *num.a << ", by adress: " << &num.a <<
std::endl;
}
int main()
{
std::cout << "\nLifetime extention:" << std::endl;
{
const C& ext_num = return_num();
std::cout << "From main() 1 : num = " << *(ext_num.a) << ", by resource
adress: " << &(*ext_num.a) << std::endl;
}
std::cout << "\nPassing by reference:" << std::endl;
{
C num(20);
std::cout << "From main() 2 : num = " << *num.a << ", by adress: " << &num.a
<< std::endl;
pass_num(num);
}
return 0;
}
The above code produces below output:
Lifetime extention:
From return_num(): num = 20, Address of resource a : 0x7fffeca99280
Move!!Address resource a 0x7fffeca99280, Address of resource rhs.a0x7fffeca99280
Value of a:: 20
From main() 1 : num = 20, by resource adress: 0x7fffeca99280
Passing by reference:
From main() 2 : num = 20, by adress: 0x7ffff466f388
From pass_num(): num = 20, by adress: 0x7ffff466f388
I hope it helps!
Imagine this function:
int getNumber(){
int num = 10;
return num;
}
This function does not return num as an object, it returns a no-named copy of it (r-value, if you will) with the same value. Therefore, it has a different address.
The same thing happens with your return_num function.
I suspect that taking the address of a member is inhibiting the optimization because the compiler doesn't know how to deal with all the possible edge cases. Eliminating taking the address of the member makes the optimization work.
#include <iostream>
struct C
{
C(const int new_a) { a = new_a; };
int a = 0;
struct C* t = this;
};
C return_num()
{
C num(20);
std::cout << "From func(): num = " << num.a << ", by adress: " << num.t << std::endl;
return num;
}
void pass_num(const C& num)
{
std::cout << "From func(): num = " << num.a << ", by adress: " << num.t << std::endl;
}
int main()
{
std::cout << "\nLifetime extention:" << std::endl;
{
const C& ext_num = return_num();
std::cout << "From main(): num = " << ext_num.a << ", by adress: " << ext_num.t << std::endl;
}
std::cout << "\nPassing by reference:" << std::endl;
{
C num(20);
std::cout << "From main(): num = " << num.a << ", by adress: " << num.t << std::endl;
pass_num(num);
}
}
Lifetime extention:
From func(): num = 20, by adress: 0x7ffd61f48a50
From main(): num = 20, by adress: 0x7ffd61f48a50
Passing by reference:
From main(): num = 20, by adress: 0x7ffd61f48a90
From func(): num = 20, by adress: 0x7ffd61f48a90
I want to pass the pointer to a structure(variables of this structure is an array with elements that have value x and y) to the constructor. Next I want to assign values x and y of each variable of this structure to the similar variable values of the structure in the class.
class Convex_quadrliteral
{
protected:
struct VC {
float x, y;
} vertice_coordinate[4];
public:
Convex_quadrliteral (VC *pointerVC);
};
Convex_quadrliteral::Convex_quadrliteral (VC *pointerVC) {
cout << "\nObject is being created" << endl;
for (int i = 0; i < 4; i++) //variable initialisation
{
vertice_coordinate[i].x = pointerVC[i].x;
vertice_coordinate[i].y = pointerVC[i].y;
}
//object's properties output
cout << "Properties: " << endl
<< "A (" << vertice_coordinate[0].x << ", " << vertice_coordinate[0].y << ")" << endl
<< "B (" << vertice_coordinate[1].x << ", " << vertice_coordinate[1].y << ")" << endl
<< "C (" << vertice_coordinate[2].x << ", " << vertice_coordinate[2].y << ")" << endl
<< "D (" << vertice_coordinate[3].x << ", " << vertice_coordinate[3].y << ")" << endl;
}
int main()
{
struct vertice_coordinate
{
float x, y;
};
vertice_coordinate *pointerVC = new vertice_coordinate[4];
for (int i = 0; i < 4; i++) {
pointerVC[i].x = 2;
pointerVC[i].y = 2;
}
Convex_quadrliteral figure_1(pointerVC);
I expect the output:
A(2, 2)
B(2, 2)
C(2, 2)
D(2, 2)
The output is error: no declaration matches 'Convex_quadrliteral::Convex_quadrliteral(Convex_quadrliteral::VC*)'C onvex_quadrliteral::Convex_quadrliteral (VC *pointerVC)
You re-define your VC struct, and even though the struct looks identical, the compiler will treat them as two different types. Define one struct and use it in both your class and in main.
I cant figure out why the output of this program is what it is. Maybe some one can help me out.
And why does the reference of double Pointer: 0062FB78?
Why does the reference of dereferenced double pointer = 0062FAA0?
Should'nt these be flipped?
0062FB78 is the address of x
I am guess 0062FAA0 is the address of the double Pointer?
#include <iostream>
void print(int x) {
std::cout << "value: " << (x) << "\n";
std::cout << "reference: " << (&x) << "\n";
//std::cout << (*x) << "\n";
}
void printPointer(int *x) {
std::cout << "value: " << x << "\n";
std::cout << "reference: " << &x << "\n";
std::cout << "dereference:" << *x << "\n";
}
void printDoublePointer(int **x) {
std::cout << "value: " << x << "\n";
std::cout << "reference: " << &x << "\n";
std::cout << "dereference:" << *x << "\n";
printPointer(*x);
}
void printTripplePointer(int ***x) {
std::cout << "value:" << x << "\n";
std::cout << "reference:" << &x << "\n";
std::cout << "dereference:" << *x << "\n";
printDoublePointer(*x);
}
void print(char* string) {
std::cout << "\n" << string << "\n";
}
int main()
{
int x = 19;
int *y; // y is a address space
y = &x; // &y now points to the address of x, *y now has the value of x
int **doublePointer = &y;
print(x);
printPointer(y);
printDoublePointer(doublePointer);
print("doublePointer");
std::cin >> x;
}
x
value: 19
reference: 0062FBB78
y
value: 0062FC7C
reference: 0062FBB78
defererence: 19
doublePointer
value: 0062FC58
reference of double Pointer: 0062FB78
dereference of doble Pointer: 0062FC7C
value of dereferenced double pointer: 0062FC7C
reference of dereferenced double pointer: 0062FAA0
dereference: 19
Before going over you problem, let's first agree that after calling y= &x, y is not a reference to x, but rather the address of x.
Now, let's examine the call to print
If you pay close attention, we pass the variable by-value, so this method will actually print the value 19, but the address will belong to a temp copy of x.
If we would have changed the prototype to the following one, the address of x printed here will be equal to the address of y printed in the method printPointer
void print(int & x) {
std::cout << __PRETTY_FUNCTION__ << "\n";
std::cout << "value: " << (x) << "\n";
std::cout << "reference: " << (&x) << "\n";
}
Regarding your other concern, these too occur because you pass the pointers by-value and not by-reference.
This simple program shows that everything works just fine:
int main()
{
int x = 19;
int *y = &x;
int **z = &y;
std::cout << x << "\t" << &x << std::endl;
std::cout << y << "\t" << &y << "\t" << *y << std::endl;
std::cout << z << "\t" << &z << "\t" << *z << std::endl;
}
I'm trying to execute the following code:
#include <iostream>
using namespace std;
class ABC {
private:
int x, y;
public:
ABC(){
cout << "Default constructor called!" << endl;
ABC(2, 3);
cout << x << " " << y << endl;
}
ABC(int i, int j){
cout << "Parameterized constructor called with parameters "<< i << " " << j << "!" << endl;
x = i;
y = j;
cout << x << " " << y << endl;
}
};
int main(){
ABC a;
return 0;
}
I am getting the following output:
Default constructor called!
Parameterized constructor called with parameters 2 3!
2 3
-858993460 -858993460
Shouldn't the member variables be initialized with values 2 and 3?
ABC(2, 3); doesn't call the constructor to initialize the members, it just create a temporary variable which will be destroyed immediately.
If you meant delegating constructor you should:
ABC() : ABC(2, 3) {
cout << "Default constructor called!" << endl;
cout << x << " " << y << endl;
}
Note this is a C++11 feature. You can add a member function if you can't use C++11.
class ABC {
private:
int x, y;
init(int i, int j) {
x = i;
y = j;
}
public:
ABC(){
cout << "Default constructor called!" << endl;
init(2, 3);
cout << x << " " << y << endl;
}
ABC(int i, int j){
cout << "Parameterized constructor called with parameters "<< i << " " << j << "!" << endl;
init(i, j);
cout << x << " " << y << endl;
}
};
You create a temporary variable in ABC() body. You can use this syntax to overcome this:
class ABC
{
private:
int x, y;
public:
ABC() : ABC(2,3)
{
std::cout << "Default constructor called!" << std::endl;
}
ABC(int i, int j)
{
std::cout << "Parameterized constructor called with parameters "<< i << " " << j << "!" << std::endl;
x = i;
y = j;
std::cout << x << " " << y << std::endl;
}
};
#include<iostream>
using namespace std;
class a
{
private:
int x;
int y;
public:
int getx()
{
return x;
}
int gety()
{
return y;
}
a()
{
x = 100;
y = 100;
}
void xmin()
{
x--;
}
void ab(a x)
{
x.xmin(); x.xmin(); x.xmin(); x.xmin();
}
};
void main()
{
a xx;
a yy;
cout << "xx" << endl;
cout << "x : " << xx.getx() << "y : " << xx.gety()<<endl;
cout << "yy" << endl;
cout << "x : " << yy.getx() << "y : " << yy.gety()<<endl;
xx.ab(yy);
cout << "xx" << endl;
cout << "x : " << xx.getx() << "y : " << xx.gety() << endl;
cout << "yy" << endl;
cout << "x : " << yy.getx() << "y : " << yy.gety() << endl;
}
Why the function x.xmin() in void ab(a x) cannot be executed properly? (The value of x didn't change as the function of xmin() decrease the value of x by 1.
This is the simple version of my code so that will be easier to understand :)
void ab(a x)
That takes its argument by value. The function modifies a local copy of the argument, so the caller won't see any changes. If you want the function to modify the caller's object, then pass by reference:
void ab(a & x)
^