Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ function in namespace won't work?

Tags:

c++

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;
}
like image 413
Tom Avatar asked Dec 04 '25 23:12

Tom


1 Answers

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.

like image 199
Pete Becker Avatar answered Dec 06 '25 13:12

Pete Becker