In this article we will discuss how to capture member variables from outer scope.

Suppose we have a class OddCounter to keep the track of odd numbers read by the object. Inside its member function we are creating a lambda function and passing to a STL algorithm std::for_each.

Now this lambda function needs to capture member variable mCounter. How to do it?

If we try to capture member variable directly by value or reference, then it will not work i.e.

Wrong way to capture member variable — Compile Error

class OddCounter
{
	// tracks the count of odd numbers encountered
	int mCounter = 0;
public:
	int getCount()
	{
		return mCounter;
	}
	void update(std::vector<int> & vec)
	{
		// Capturing member variable by value will not work
                // Will result in Compile Error
		std::for_each(vec.begin(), vec.end(), [mCounter](int element){
			if(element % 2)
				mCounter++; // Accessing member variable from outer scope
		});
	}
};

It will result in compile error. So how to capture member variables inside lambda function ?

Capturing Member variables inside Lambda Function

To capture the member variables inside lambda function, capture the “this” pointer by value i.e.

std::for_each(vec.begin(), vec.end(), [this](int element){
//....
}

Capturing this pointer inside lambda function will automatically capture all the member variables for this object inside lambda.

Complete example is as follows,

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>

class OddCounter
{
	// tracks the count of odd numbers encountered
	int mCounter = 0;
public:
	int getCount()
	{
		return mCounter;
	}
	void update(std::vector<int> & vec)
	{
		// Traverse the vector and increment mCounter if element is odd
		// this is captured by value inside lambda
		std::for_each(vec.begin(), vec.end(), [this](int element){
			if(element % 2)
				mCounter++; // Accessing member variable from outer scope
		});
	}
};


int main(int argc, char **argv)
{
	std::vector<int> vec = {12,3,2,1,8,9,0,2,3,9,7};

	OddCounter counterObj;

	//Passing the vector to OddCounter object
	counterObj.update(vec);

	int count = counterObj.getCount();

	std::cout<<"Counter = "<<count<<std::endl;
	return 0;
}


Output
Counter = 6

Now as “this” is copied by value inside lambda, all member variables from outer scope can be accessed directly.

To compile the above code in linux use following command,

g++ –std=c++11 example.cpp

 

C++11 Lambda Function : Example & Tutorial

C++11 Lambda : How to capture local variables inside Lambda ?

Join a list of 2000+ Programmers for latest Tips & Tutorials