+ 8
Please explain this C++ challenge
Could someone please explain this C++ challenge: class A { public: A() {cout<<"Its A class";} A(int a=0) {cout<<"A";} }; int main() { A a(); } This has no output. Shouldn't be called constructor A() in this case? What constructor is called when instantiating a, since there is no output? What should be done to call A()?
6 Answers
+ 7
You know, A a(); never calls the constructor.
You have instead, declared a prototype of a function a, that takes no arguments and return an object of class A. :)
Use A a, to call the constructor.
And I do think that you may get an error in your code, as the constructors are ambiguous. The compiler won't be able to guess if you wanted to call A() or A(int) with the default 0.
So, there is an error in this challenge. You must report it.
+ 5
no, it seems it is ok with challenge. its just declared prototype and never defined function, but that is not an error.
i really got confused here, thank you
+ 5
The error is not with the prototype, but the constructor ambiguity. Thats all.
Well, since you don't need to see all details like these in challenges, its fine.
+ 5
Thats the error I was talking about :).
You may declare functions, but you can't create objects using the default constructor. You need to provide an int in the parenthesis.
+ 4
i tried it on code playground, it worked fine, "no output".
however if i tried
A a;
there is an error. so only if you try to instantiate the class A.
+ 2
That is interesting exercise :)