views:

883

answers:

3

I was trying to write up a class in c++, and I came across a rather odd problem: calling outside functions inside of a class that have the same name as the class. It's kinda confusing, so here's an example:

void A(char* D) {
  printf(D);
}

class A 
{
public:
  A(int B);
  void C();
};

A::A(int B) {
  // something here
}

void A::C() {
  A("Hello, World.");
}

The compiler complains at the second to last line that it can't find a function A(char*), because it is inside the class, and the constructor has the same name as the function. I could write another function outside, like:

ousideA(char* D) {
  A(D);
}

And then call outsideA inside of A::C, but this seems like a silly solution to the problem. Anyone know of a more proper way to solve this?

+2  A: 

I suggest you use namespaces. Put your class in a different namespace than the function.

namespace my_namespace1
{

void A() {}

}

namespace my_namespace2
{

struct A {};

}


int main()
{
    my_namespace1::A();
    my_namespace2::A my_a;    
}

Of course, the real question is, why do you have a class and a function with a different name? A good easy rule is to make classes named WithABeginningCapitalLetter and functions withoutOne. Then you will never have this problem. Of course, the STL doesn't do this...

rlbond
+7  A: 
::A(D);

should work fine. Basically it is saying "use the A found in the global namespace"

Evan Teran
+2  A: 

Use the scope resolution operator :: to access the name from the global scope:

void A::C() {
  ::A("Hello, world.");
}
Adam Rosenfield