Thread: x = foo();

  1. #1

    x = foo();

    Alright first lets look at a sample piece of code before I ask my question.

    class foo
                foo() { x = 0; }
                void put( int i ) { x = i; }
                int    get( void ) { return x; }
               int x;
    int main()
           foo bar;
           bar.put( 1 );
           cout << bar.get() << endl;
           bar = foo();
           cout << bar.get() << endl;
    Ok my question is about the line "bar = foo();" Now I know what happens to bar, when i call bar.get() I output a 0. But what I'm wondering is, what exactly is that line of code doing there? Is it making bar call it's constructor again, or is it creating a temporary object of foo and copying that to bar then freeing itself, or not freeing itself staying in memory wasting space? Or is it doing something not in that list?


  2. #2
    Skunkmeister Stoned_Coder's Avatar
    Join Date
    Aug 2001
    it does 3 things. Firstly a temporary foo object is made with the default constructor. Then the assignment operator is called to assign that temp to bar.Then finally the temp is destroyed by calling the destructor.
    Free the weed!! Class B to class C is not good enough!!
    And the FAQ is here :-

  3. #3
    Ah ok that's what I figured what was going on but untill I was absolute I just had to ask. Thanks.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Recursive Function
    By Codedecode in forum C++ Programming
    Replies: 5
    Last Post: 06-07-2008, 02:14 AM
  2. foo
    By goran00 in forum C Programming
    Replies: 6
    Last Post: 04-04-2008, 12:22 AM
  3. array -- foo, &foo and &foo[0]
    By George2 in forum C Programming
    Replies: 9
    Last Post: 08-14-2007, 01:22 PM
  4. anyone here hate when foo bar baz is used in example code?
    By shintaro in forum A Brief History of
    Replies: 18
    Last Post: 09-26-2006, 07:07 AM
  5. Couple of Q's.....
    By oobootsy1 in forum C++ Programming
    Replies: 18
    Last Post: 02-23-2004, 02:03 PM