*this and .c_str()

This is a discussion on *this and .c_str() within the C++ Programming forums, part of the General Programming Boards category; 1st question: what does c_str() do ? when should i use and include it ? 2nd question: what does 'this ...

  1. #1
    Registered User
    Join Date
    Oct 2003
    Posts
    55

    *this and .c_str()

    1st question:
    what does c_str() do ? when should i use and include it ?

    2nd question:
    what does 'this pointer' do ? when should i use and include it ?

  2. #2
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,796
    >what does c_str() do ? when should i use and include it ?
    It returns the contents of a string in nul terminated C-style string format. You should only need it for functions that take char * or const char * instead of std::string. For example, printf.

    >what does 'this pointer' do ? when should i use and include it ?
    Every object has a pointer to itself, called this. Any time you need an object to refer to itself you can use it. For example, when implementing the assignment, you can use this to check for self assignment:
    Code:
    Test& Test::operator= ( const Test& rhs )
    {
      if ( this == &rhs )
        return *this;
      ...
    }
    My best code is written with the delete key.

  3. #3
    Registered User
    Join Date
    Oct 2003
    Posts
    55
    Code:
    void test(int x)
    {
       int x;
       this->x=x;
    }
    the above code means ?

  4. #4
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,796
    Assuming it is a member function, it means you will get a compiler diagnostic complaining about a redefinition of a formal parameter. If you remove the local definition of x then it means the object member x is assigned the value of the parameter x:
    Code:
    #include <iostream>
    
    using namespace std;
    
    class C {
    public:
      void test(int x)
      {
        //int x;
        this->x=x;
      }
      int x;
    };
    
    int main()
    {
      C c;
    
      c.test(5);
      cout<< c.x <<endl;
    }
    My best code is written with the delete key.

Popular pages Recent additions subscribe to a feed

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