On Aug 2, 11:54*pm, raicuandi <raicua...@gmail.com> wrote:
> On Aug 3, 2:44*pm, AhmedB <ahmed.bad...@gmail.com> wrote:
>
>
>
> > Hi,
>
> > I wrote this program, compiled it and ran it with the expectation that
> > I will get two printed lines (one from each ctor):
>
> > #include <cstdio>
> > class A
> > {
> > * * * * public:
> > * * * * A(int a)
> > * * * * {
> > * * * * * * * * fprintf(stderr, "A(int a)\n");
> > * * * * * * * * i = a;
> > * * * * }
> > * * * * A(const A& a)
> > * * * * {
> > * * * * * * * * fprintf(stderr, "A(const A& a)\n");
> > * * * * * * * * i = a.i;
> > * * * * }
> > * * * * private:
> > * * * * int i;
> > * * * * private:
> > * * * * const A& operator= (const A&)
> > * * * * {
> > * * * * }
>
> > };
>
> > int main()
> > {
> > * * * * A a = A(5);
> > * * * * return 0;
>
> > }
>
> > I only got:
>
> > A(int a)
>
> > So I thought Ok, maybe the compiler is compiling the
>
> > A a = A(5); to be
>
> > A a(5) somehow,
>
> > So I went ahead and changed the code to make the copy constructor
> > explicit, as follows:
>
> > #include <cstdio>
> > class A
> > {
> > * * * * public:
> > * * * * A(int a)
> > * * * * {
> > * * * * * * * * fprintf(stderr, "A(int a)\n");
> > * * * * * * * * i = a;
> > * * * * }
> > * * * * explicit A(const A& a)
> > * * * * {
> > * * * * * * * * fprintf(stderr, "A(const A& a)\n");
> > * * * * * * * * i = a.i;
> > * * * * }
> > * * * * private:
> > * * * * int i;
> > * * * * private:
> > * * * * const A& operator= (const A&)
> > * * * * {
> > * * * * }
>
> > };
>
> > int main()
> > {
> > * * * * A a = A(5);
> > * * * * return 0;
>
> > }
>
> > Then I tried compiling the code and got the following:
>
> > test.cc: In function ‘int main()’:
> > test.cc:42: error: no matching function for call to ‘A::A(A)’
> > test.cc:18: note: candidates are: A::A(int)
>
> > So my question is, if my understanding is correct and this is the
> > sequence that is going on:
> > 1. An A::A(int) constructor is used to convert an int to an A,
> > followed by
> > 2. An A::A(const A&) constructor is used to copy the temporary A
> > and this is why I'm getting the compilation error when I make the
> > A::A(const A&) explicit, then why am I not getting two printed lines
> > in the first case? Is there something else going on here that I'm not
> > paying attention to?
>
> > This code is compiled/run on a Suse 10.3 Linux box with gcc/g++
> > version 4.2.1.
>
> > Regards,
> > Ahmed
>
> This has got to be the most pointless exercise I've seen this week. 
> Why would anyone *want* an extra copy-constructor?..
Not a matter of *want* but sometimes one wants to check their
knowledge and understanding with a simple example, and boom they get
surprised due to the compiler doing some optimization. I'm one of
those who are interested in _understanding_ how/why things work/don't
work, rather than taking things for granted and settling for 'that's
the way it works' type of thought.