why copy constructor is not being called?

Discussion in 'C++' started by suresh, Apr 15, 2008.

  1. suresh

    suresh Guest

    Hi

    Could you please tell why copy constructor is not called in the first
    line in main(), as mentioned in the text books. I used g++ version
    4.1.2 on debian etch

    thanks
    suresh

    # include <iostream>
    using namespace std;
    class base
    {
    char s;
    public:
    base( ){cout<< "construction" << endl;}
    base(const char a ) {cout << "construction with arg" << endl;}
    base(const base & a){cout <<"copy constructor" << endl;}
    base & operator=(const base & a){cout << "assignment operator" <<
    endl;}
    ~base( ) {cout << "destruction" << endl;}
    };

    main ( )
    {
    base b1 = 'x'; //why copy constructor is NOT called here as given in
    books?
    base b2 = b1; //copy constructor is called

    }
     
    suresh, Apr 15, 2008
    #1
    1. Advertising

  2. suresh

    Rolf Magnus Guest

    Pete Becker wrote:

    > the compiler should construct a temporary object of type base from the
    > argument 'x', then copy that temporary into b1. However, the answer to
    > the original question is that the compiler is permitted to elide the
    > copy if the copy constructor has no side effects,


    Actually, the compiler is also allowed to do this if the constructor does
    have side effects. Printing to cout is a side effect.
     
    Rolf Magnus, Apr 15, 2008
    #2
    1. Advertising

  3. suresh wrote:
    > ...
    > Could you please tell why copy constructor is not called in the first
    > line in main(), as mentioned in the text books. I used g++ version
    > 4.1.2 on debian etch
    > ...


    Because the language specification explicitly allows the compiler to
    optimize away the copying of temporary objects, even if the
    copy-constructor has any side-effects.

    In other words, the constructor might get called. Or it might not get
    called. It might depend on the compiler, on the compiler settings and
    even on the concrete context in the code. Just don't rely on it.

    --
    Best regards,
    Andrey Tarasevich
     
    Andrey Tarasevich, Apr 15, 2008
    #3
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Apricot
    Replies:
    4
    Views:
    559
    velthuijsen
    Apr 16, 2004
  2. Tom Widmer
    Replies:
    1
    Views:
    522
    Victor Bazarov
    Nov 17, 2004
  3. Mr. SweatyFinger
    Replies:
    2
    Views:
    2,211
    Smokey Grindel
    Dec 2, 2006
  4. Replies:
    9
    Views:
    1,878
    Alf P. Steinbach
    Oct 14, 2006
  5. cinsk
    Replies:
    35
    Views:
    2,724
    James Kanze
    Oct 11, 2010
Loading...

Share This Page