+ 2

Hey friends please explain me this code and say why its output is a?

#include <iostream> using namespace std; class A { public : A(){cout<<"a";} A(const & x){cout <<"b";} }; int main() { A x; A y(x); return 0; } //output is a but why ?

12th Sep 2018, 6:49 PM
Albert Whittaker :Shaken To Code
Albert Whittaker :Shaken To Code - avatar
3 Antworten
+ 1
A y(x) executes copy constructor which has signature A(const A& x). That constructor was generated by default and didn't perform any output.
13th Sep 2018, 4:39 AM
Sergey Ushakov
Sergey Ushakov - avatar
+ 5
The definition, A(const & x) { cout <<"b"; } In many compilers throws an error indicates that the 'x' has no type. In fact, the above definition refers to a ctor (copy constructor) by which an object can be initialized using another object. But the class' name as the type of 'x' is missing. The truth is if the above ctor (if it has been correctly defined) gets called by A y(x); The output must be contained the letter 'b', as well. So we conclude that, since the -fpermissive flag is on by default in SL's compiler, and according to the GNU doc ¹ " -fpermissive Downgrade some diagnostics about nonconformant code from [errors to warnings]. Thus, using -fpermissive will allow some nonconforming code to compile. " the code gets compiled, but won't show the correct result. _____ ¹ http://gcc.gnu.org/onlinedocs/gcc-4.0.4/gcc/C_002b_002b-Dialect-Options.html#index-fpermissive-140
12th Sep 2018, 8:17 PM
Babak
Babak - avatar
0
this does not compile
12th Sep 2018, 7:05 PM
Bebida Roja
Bebida Roja - avatar