Thread: Function returning *this pointer

  1. #1
    Registered User
    Join Date
    Jan 2012
    Posts
    9

    Function returning *this pointer

    Hi, I'm new to C++ and OO programming and I have a question about this code:

    Code:
    #include <iostream>
    using namespace std;
    
    class A{
    
        private:
            int a;
            int b;
    
        public:
            A(int aa=0,int bb=0){a=aa;b=bb;}
            int geta(){return a;}
            int getb(){return b;}
            A foo(){return *this;}
            A& foo2(){return *this;}
    
    };
    
    
    int main(){
    
    A obj;
    
    obj.foo()=4;
    
    return 0;
    }
    How is this allowed obj.foo()=4;?? I know that foo2 returns reference to obj object, but I don't understand how foo works...

  2. #2
    Officially An Architect brewbuck's Avatar
    Join Date
    Mar 2007
    Location
    Portland, OR
    Posts
    7,396
    It involves the default assignment operator and an implicit call to the constructor of A... If you change "int aa=0,int bb=0" to "int aa,int bb" it should no longer compile.
    Code:
    //try
    //{
    	if (a) do { f( b); } while(1);
    	else   do { f(!b); } while(1);
    //}

  3. #3
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,318
    Of course it does not result in 'obj' being modified, since the assignment merely modifies the copy which was returned by 'foo'.
    My homepage
    Advice: Take only as directed - If symptoms persist, please see your debugger

    Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"

  4. #4
    Registered User
    Join Date
    Apr 2006
    Posts
    2,149
    The reason that this works is that in general, you can call non-const methods of temporaries. Like this:
    Code:
    A().foo();
    Assignment for classes is considered a method. This:
    Code:
    A()=4
    Is sugar for this:
    Code:
    A().operator=(4)
    In contrast, primitive types don't implement assignment as a method, so this is not allowed:
    Code:
    int()=4;
    It is too clear and so it is hard to see.
    A dunce once searched for fire with a lighted lantern.
    Had he known what fire was,
    He could have cooked his rice much sooner.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Address off when returning pointer from function.
    By dtow1 in forum C Programming
    Replies: 3
    Last Post: 09-14-2011, 02:11 PM
  2. Replies: 0
    Last Post: 05-29-2009, 05:48 AM
  3. Returning pointer from function question
    By Rune Hunter in forum C++ Programming
    Replies: 12
    Last Post: 07-12-2007, 09:45 AM
  4. function returning pointer
    By blue_gene in forum C Programming
    Replies: 7
    Last Post: 04-19-2004, 02:35 PM