Thursday, July 30, 2009

Want to know reason for output of this C++ Code....?

#include%26lt;iostream.h%26gt;


class A


{ int a,b;


public:


A(A%26amp; a1)


{


cout%26lt;%26lt;"Copy Constructor\n";


}


A()


{


cout%26lt;%26lt;"Constructor A()\n";


}





A(int a=7,int b=8)


{


this-%26gt;a=a;


this-%26gt;b=b;


cout%26lt;%26lt;"this-%26gt;a="%26lt;%26lt;this-%26gt;a%26lt;%26lt;endl;


cout%26lt;%26lt;"this-%26gt;b="%26lt;%26lt;this-%26gt;b%26lt;%26lt;endl;


cout%26lt;%26lt;"*******\n";


}


void operator ()()


{


cout%26lt;%26lt;"overloaded operator ()\n";


}


};


void main()


{


A a1();


}





...for this A a1();


which constructor is called...?because..nothing is printed on screen or console...?Why?

Want to know reason for output of this C++ Code....?
It usually should have called the constructor A() if you are making the object in maner "A a1;" in the main function. But also you have overloaded the operator "()". SO, it makes a confusion and actually none of the output from the above constructors are called. Another thing, its not a good thing to inital values in parameters. I've often faced these problems when I overloaded the "()" operator. For any further questions you can contact me.
Reply:The compiler does not know which constructor to use for this statement. Will it be A() or A(int,int)? Though it doesn't show any errors if you write it this way, it won't display anything! For making it work do one of the following:


1. when you declared the A(int,int) remove the initial values; this is the reason why the compiler doesn't know if it's this one or the other one.


2. use values when building a1 like A a1(1,1) for example. This way the compiler knows exactly which constructor to call.


3. the first constructor is useless and it's causing you problems; simply delete it!
Reply:#include%26lt;iostream.h%26gt;


class A


{ int a,b;


public:


A(A%26amp; a1)


{


cout%26lt;%26lt;"Copy Constructor\n";


}


A()


{


cout%26lt;%26lt;"Constructor A()\n";


}





A(int a=7,int b=8)


{


this-%26gt;a=a;


this-%26gt;b=b;


cout%26lt;%26lt;"this-%26gt;a="%26lt;%26lt;this-%26gt;a%26lt;%26lt;endl;


cout%26lt;%26lt;"this-%26gt;b="%26lt;%26lt;this-%26gt;b%26lt;%26lt;endl;


cout%26lt;%26lt;"*******\n";


}


void operator()()


{


cout%26lt;%26lt;"overloaded operator ()\n";


}


};


void main()


{


A a1();





void getch();


return 0;


}





The following will not display the output because


the cout are declared inside the class and not in the main()


The reason is due to that a class does not stores any object it creates objects at runing time and destroys them


so it should use constructor and destructor. You should create objects in the main().


No comments:

Post a Comment