0

How can i call class constructor .

I can't call class constructor i don't know why but when i define class in the main function . it must be call constructor automatically but it does not work . . https://code.sololearn.com/caqich0G74A8/?ref=app

3rd Aug 2018, 1:19 PM
Fidan Rli
Fidan Rli - avatar
13 ответов
0
write without brackets. A a;
3rd Aug 2018, 1:46 PM
nillyhan
0
You're missing a semi-colon at the end of class declaration. And you don't need parenthesis on object. A a; //not A a();
3rd Aug 2018, 1:46 PM
Akib
Akib - avatar
0
Akib Reza nillyhan i added something . please look at again . and when i write A a an error occurs.
3rd Aug 2018, 1:53 PM
Fidan Rli
Fidan Rli - avatar
0
try to do it in second constructor. A(int a=5) : k(a) {} and call it from main like, A a(5); or A a(6);
3rd Aug 2018, 1:55 PM
nillyhan
0
nillyhan i did it and the second constructor worked . but first one didn't. i wanted the first one to work .
3rd Aug 2018, 2:02 PM
Fidan Rli
Fidan Rli - avatar
0
first one is default constructor. you must not put any parameter inside it's parenthesis. write it as A() : k(5) {}. Now calling " A a; " from main() would put 5 into k by default.
3rd Aug 2018, 2:07 PM
nillyhan
0
nillyhan i did everything as you said . but an error occurred again.
3rd Aug 2018, 2:27 PM
Fidan Rli
Fidan Rli - avatar
0
nillyhan please look at my code again.
3rd Aug 2018, 2:28 PM
Fidan Rli
Fidan Rli - avatar
0
A a() is a function declaration, a function called a, returning an object A and taking no arguments. It's not a variable definition. A a() is also called a vexing parse, because this is not what you would expect to happen and a common beginner mistake. A a; would make it a variable without arguments. Now A has to call a suitable constructor. A has 2 constructors: 1. A(), a constructor taking 0 arguments 2. A(int a=5), a constructor taking 0 or 1 argument Which one should it call? A() or A(int a=5)? It doesn't know either, this is an ambiguity error and causes the program to be rejected. So either remove the default constructor or the default parameter to fix that.
3rd Aug 2018, 2:32 PM
Dennis
Dennis - avatar
0
oh I missed it earlier, sorry. edit the second constructor. remove "=" and write it like A(int a) : k(a) {}
3rd Aug 2018, 2:32 PM
nillyhan
0
yes, as Dennis said
3rd Aug 2018, 2:33 PM
nillyhan
0
Dennis oh i got it thanks . the compiler does not know which one has to call.
3rd Aug 2018, 2:50 PM
Fidan Rli
Fidan Rli - avatar
0
nillyhan thanks a lot
3rd Aug 2018, 2:50 PM
Fidan Rli
Fidan Rli - avatar