Possible Duplicate:
What are the differences between pointer variable and reference variable in C++?
What are the distinctions between the various symbols (*,&, etc) combined with parameters?
I'm having a bit of trouble getting my head around this example code pasted below. Specifically, the function Buf& operator=( const Buf & );
. From what I understand, this function expects an address of the object of class Buf
to be returned. Two questions arise:
Is it equally applicable to declare this as
Buf* operator=( const Buf* );
, sinceBuf*
is also an address of an instance of classBuf
? If not, why not? If so, is it just a preference of coding sytle? Which is preferable?In the corresponding function definition,
*this
is returned. From what I understand,this
is a pointer, or address corresponding to the object of classBuf
. So*this
is what the pointer points to, i.e. an object of classBuf
. Is this in conflict with returningBuf*
? Should the function returnthis
instead of*this
?
I guess I'm having one of those days today... please somebody help!!
using namespace std; class Buf { public: Buf( char* szBuffer, size_t sizeOfBuffer ); Buf& operator=( const Buf & ); void Display() { cout << buffer << endl; } private: char* buffer; size_t sizeOfBuffer; }; Buf::Buf( char* szBuffer, size_t sizeOfBuffer ) { sizeOfBuffer++; // account for a NULL terminator buffer = new char[ sizeOfBuffer ]; if (buffer) { strcpy_s( buffer, sizeOfBuffer, szBuffer ); sizeOfBuffer = sizeOfBuffer; } } Buf& Buf::operator=( const Buf &otherbuf ) { if( &otherbuf != this ) { if (buffer) delete [] buffer; sizeOfBuffer = strlen( otherbuf.buffer ) + 1; buffer = new char[sizeOfBuffer]; strcpy_s( buffer, sizeOfBuffer, otherbuf.buffer ); } return *this; } int main() { Buf myBuf( "my buffer", 10 ); Buf yourBuf( "your buffer", 12 ); // Display 'my buffer' myBuf.Display(); // assignment opperator myBuf = yourBuf; // Display 'your buffer' myBuf.Display(); }