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?
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.
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.
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.
Yes, but only if the two classes have the same name.
::A("Hello, world.");
should work fine. Basically it is saying "use the A
found in the global namespace"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With