arrow functions c++ code example
Example 1: lambda c++
#include <iostream>
#include <string>
auto makeWalrus(const std::string& name)
{
return [&]() {
std::cout << "I am a walrus, my name is " << name << '\n';
};
}
int main()
{
auto sayName{ makeWalrus("Roofus") };
sayName();
return 0;
}
Example 2: arrow operator c++
#include <iostream>
using std::cout;
class Entity {
public:
const char* name = nullptr;
private:
int x, y;
public:
Entity(int x, int y, const char* name)
: x(x), y(y), name(name) {
printEntityPosition(this);
}
int getX() { return x; }
int getY() { return y; }
friend void printEntityPosition(Entity* e);
};
void printEntityPosition(Entity* e) {
cout << "Position: " << e->getX() << ", " << e->getY() << "\n";
}
int main() {
Entity* pointer = new Entity(1, 1, "Fred");
cout << (*pointer).name << "\n";
cout << pointer->name << "\n";
Entity not_a_pointer(2, 2, "Derf");
cout << not_a_pointer.name << "\n";
std::cin.get();
return 0;
}