0
C++ parentheses
#include <iostream> using namespace std; class A {public: A(){cout<<3;} void test(){cout<<4;}}; int main() { A a(); return 0; } In this snippet, if I use A a; the constructor is called. If I use A a(); it says no output and does not compile error or run time error. Can someone explain me what the parentheses do?
6 odpowiedzi
+ 8
A() is the default constructor, it has no parameters/arguments
We can specify a custom constructor by supplying parameters/arguments
. for example
class A {
A(); //default constructor
A(int value); // custom constructor
when creating an object with a custom constructor we specify the parameters/arguments inside the parentheses.
example:
A a(2);
when using the default constructor we do not use parentheses.
example:
A a;
See here for more information on constructors and their correct usage.
https://www.ibm.com/support/knowledgecenter/en/SSLTBW_2.2.0/com.ibm.zos.v2r2.cbclx01/cplr376.htm
+ 6
n3337 8.2/1
"... the choice is between a function declaration with a redundant set of parentheses around a parameter name and an object declaration with a function-style cast as the initializer. Just as for the ambiguities mentioned in 6.8, the resolution is to consider any construct that could possibly be a declaration a declaration."
Similar issue for your case.
A a; // declares an object a of class A.
A a(); // declares a function of return type A, which takes no arguments.
+ 6
removing return *b in this example does not affect the program as the return value is never used in main.
A's constructor is called when it is instantiated with the line A* b = new A;
Using return *b allows you to use the object A in the main function as it is returned to the calling function (in this case main)
A a() is a function with a return type of A
it is similar in structure to
int main()
[Return Type] functionName()
We can not use A a() to create a new object.
+ 5
well, sure, but it won't be what you expect.
https://code.sololearn.com/cdDo30h36ueY/?ref=app
+ 1
Thank you. I use to modify random snippets trying to get the same output with different syntax as a learning method. In this case, I removed return *b and it gave the same output. Why is that? Using return makes it possible to use A a() as a parameter?
0
Could you give me an example of when I would need A a(); but no custom constructor?