Koenig lookup or argument dependent lookup. Most of the c++ compiler supports koenig look up. Let us understand this with below example.

#include <iostream>
using namespace std;

namespace wikistack {
class A {
};
void g(A obj) {
	cout << "calling g" << endl;
}

}

int main() {
	wikistack::A obj;
	wikistack::g(obj);
	return 0;
}

we know the use of namespace key word in c++. In the above example the function g(obj) is called by using namespace wikistack. Now let us change the  above code as shown below

#include <iostream>
using namespace std;

namespace wikistack {
class A {
};
void g(A obj) {
	cout << "calling g" << endl;
}

}

int main() {
	wikistack::A obj;
	g(obj);
	return 0;
}

The above code will compile successfully even though we have not used namespace wikistack to call function g(..). how compiler does this look up? The koenig lookup feature tells the compiler to not just look at local scope, but also the namespaces that contain the argument’s type.

Koenig lookup or argument dependent lookup exercise with MCQ.

  •  will the below code compile? if yes what would be printed?
#include <iostream>
using namespace std;

namespace web {
class A {
};
void g(A obj) {
	cout << 1 << endl;
}
}

namespace site {
class B {
};
void g(B obj) {
	cout << 2 << endl;
}

}

int main() {
	web::A obj;
	g(obj);
	return 0;
}

Ans: The code would be compiled and it will give output 1. The function call g(obj ) would search inside the namespace web, because compiler would look for function g(…) according to its argument.

  • will the below code compile?
#include <iostream>
using namespace std;

class A {
public:
	struct st {
	};
	void g(st x) {

	}
};

int main() {
	A::st s;
	g(s);
	return 0;
}

Ans: No, the koenig look happens only in case of namespace.



Related Contents to follow