C++ - Calling a function inside a class with the same name as the class


C++ - Calling a function inside a class with the same name as the class



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?




Documenting class attribute

1:



Java - Method accessibility inside package-private class?
::A("Hello, world."); 
should work fine.


Static local in class member function survives class reallocation?
Basically it is saying "use the A found in the global namespace".
referencing class methods in class lists in Python


Python classes — mutability


Is it possible to detect if a class is available in Java?

2:



Best to way to re-load java classes without WebSphere re-start?
Use the scope resolution operator :: to access the name from the global scope:.
PHP Variable from extended class
void A::C() {   ::A("Hello, world."); } 


3:


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....



82 out of 100 based on 82 user ratings 1282 reviews