what does "cout<<*this;" do?!

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • bharadwaj dhuri
    New Member
    • May 2012
    • 1

    what does "cout<<*this;" do?!

    this is a statement i have within a method(function )
  • CPP freshman
    New Member
    • May 2012
    • 15

    #2
    this is the pointer to itself, so *this refers to itself. And cout<<*this prints it to the standard output.

    Eg,
    Code:
    class complex{
      int x,y;
       ....
      ostream& operator<<(ostream&);//this defines the operator "<<"
      complex& operator/(complex);
    }
    
    complex complex::operator/(complex z){
      if ((z==0)){//if divided by 0, print information
        cout<<*this<<" can't be divided by "<<z;
        return 0;
      }
      else{
        ...;
      }
    }

    Comment

    • weaknessforcats
      Recognized Expert Expert
      • Mar 2007
      • 9214

      #3
      You may not understand the this pointer.

      C++ requires every function to receive all data using arguments.

      If you look at your class member functions you will see that no member function has an argument for the class itself. Also yu will see that no member function has an argument for which object to work with.

      What happens is that the address of the object is passed in by the compiler as an invisible first argument.

      Code:
      class MyClass
      {
      private:
          int data;
      public:
          void Add(int x);
      };
      void MyClass::Add(int x)
      {
            data = x;
       }
      You can't tell what the "data" is. It might be a global variable ot it might be inside a MyClass object but you can't tell which one. The correct way to write this meber function is:
      Code:
      void MyClass::Add(int x)
      {
            this->data = x;
       }
      This says that data is inside the MyClass object pointed at by this. That makes this a MyClass*. You don't see the argument for a MyClass* in the function but it is there as an invisible first argument.

      So if this is a MyClass*, then *this must be a MyClass variable.

      Therefore, cout << *this is a call to an operator<< function that has an ostream and a MyClass argument.

      Whereas cout << this is a call to an operator<< function that has an ostream and a MyClass* argument.

      I hope this helps.
      Last edited by weaknessforcats; May 16 '12, 03:42 PM. Reason: add italics

      Comment

      Working...