Search code examples
c++identifier

How to instantiate a type named like a function


Apparently C++ lets you define both a struct/class and a function with the same name like this:

struct Foo {
    int foo;
    Foo(int foo) : foo(foo) {}
};

void Foo(int foo) {}

int main() {
    // Works, calls function
    Foo(42);

    // Doesn't work - compiler error
    Foo foo(42);
}

Is this the expected behaviour? How to create a instance of the Foo struct? How to avoid that some added library defining a function named like a type in your project causes compiler errors all over the place?


Solution

  • Yes, this is expected. There is no general way to say "I meant the class, not the function, with this name" because you are not supposed to re-use names.

    typename cannot help you here, though since Foo is a class and C++ provides backward compatibility with C's struct T type syntax, you can say class Foo or struct Foo instead:

    int main() {
        // Calls function
        Foo(42);
    
        // Constructs a `[class] Foo`
        class Foo foo(42);
    }
    

    This is something of a hack, though, and doesn't really solve the fundamental problem which is that the symbols in your program are not clearly differentiated from one another.

    Depending on your real circumstances, a namespace might solve your problem in a robust and clear way. Libraries should be using them (but often don't).

    Otherwise simply improve your names... and I don't mean by calling one Foo and the other FooClass!