This is weird and I'm trying to find the reason why would the first call to Draw on the object shape is fine while the second call to Draw on the "text" field will work only when supplying the prefix of the namespace? (ie Shapes::Draw) :
#include <iostream>
namespace Shapes
{
class Shape {
public:
Shape() {}
virtual void InnerDraw() const {
std::cout << "Shape\n";
}
};
class Square : public Shape {
public:
void InnerDraw() { std::cout << "Square\n"; }
};
void Draw(char* text) { std::cout << text; }
void Draw(const Shape& shape) {
Draw("Inner: ");
shape.InnerDraw();
}
Shape operator+(const Shape& shape1,const Shape& shape2){
return Shape();
}
}
int main() {
const Shapes::Square square;
Shapes::Shape shape(square);
Draw(shape); // No need for Shapes::
Draw("test"); // Not working. Needs Shapes:: prefix
return 0;
}
For Draw(shape) the compiler looks in the namespace where shapes type is defined to see if there's a matching function named Draw. It finds it, and calls it. For Draw("test") there is no namespace for the argument, so nowhere else to look. This is called argument dependent lookup, ADL for short.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With