Like Tree4Likes
  • 2 Post By brewbuck
  • 2 Post By King Mir

Function returning *this pointer

This is a discussion on Function returning *this pointer within the C++ Programming forums, part of the General Programming Boards category; Hi, I'm new to C++ and OO programming and I have a question about this code: Code: #include <iostream> using ...

  1. #1
    4c0 is offline
    Registered User
    Join Date
    Jan 2012

    Function returning *this pointer

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

    #include <iostream>
    using namespace std;
    class A{
            int a;
            int b;
            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;;
    return 0;
    How is this allowed;?? 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
    Portland, OR
    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.
    stahta01 and 4c0 like this.
    	if (a) do { f( b); } while(1);
    	else   do { f(!b); } while(1);

  3. #3
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    New Zealand
    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
    The reason that this works is that in general, you can call non-const methods of temporaries. Like this:
    Assignment for classes is considered a method. This:
    Is sugar for this:
    In contrast, primitive types don't implement assignment as a method, so this is not allowed:
    iMalc and 4c0 like this.
    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, 03:11 PM
  2. Replies: 0
    Last Post: 05-29-2009, 06:48 AM
  3. Returning pointer from function question
    By Rune Hunter in forum C++ Programming
    Replies: 12
    Last Post: 07-12-2007, 10:45 AM
  4. function returning pointer
    By blue_gene in forum C Programming
    Replies: 7
    Last Post: 04-19-2004, 03:35 PM

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