Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 402
Xymostech Avatar asked Jun 30 '09 03:06

Xymostech


People also ask

Can a function be the same name as the class?

Yes, It is allowed to define a method with the same name as that of a class. There is no compile-time or runtime error will occur. But this is not recommended as per coding standards in Java. Normally the constructor name and class name always the same in Java.

What is a function with the same name as another function in its class called?

Constructor. A constructor is function of a class that is called whenever an object is created. It is usually used to assign values to the variables of the class. There is also a same function which has the same name as that of its class is Destructor, It juts have tilde (~) sign at the beginning.

Is a special type of function whose name is same as the class name?

Explanation: Constructors are special because its name is same as the class name. The constructor is invoked whenever an object of its associated class is created. It is called constructor because it constructs the value of data members of the class.

Can different classes have member functions with the same name?

Yes, but only if the two classes have the same name.


1 Answers

::A("Hello, world."); 

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

like image 102
Evan Teran Avatar answered Oct 07 '22 23:10

Evan Teran