x = foo();

This is a discussion on x = foo(); within the C++ Programming forums, part of the General Programming Boards category; Alright first lets look at a sample piece of code before I ask my question. Code: class foo { public: ...

  1. #1
    HoundEYE
    Guest

    x = foo();

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

    Code:
    class foo
    {
    public:
                foo() { x = 0; }
    
                void put( int i ) { x = i; }
                int    get( void ) { return x; }
    
    private:
               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?

    Thanks.

  2. #2
    Skunkmeister Stoned_Coder's Avatar
    Join Date
    Aug 2001
    Posts
    2,572
    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 :- http://faq.cprogramming.com/cgi-bin/smartfaq.cgi

  3. #3
    HoundEYE
    Guest
    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 Cprogramming.com
    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, 01:03 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21