Hi,

I have a question regarding assignment operator.

Can I use an overloaded assignment operator for copying character pointers.

Thanks in advance.

>Can I use an overloaded assignment operator for copying character pointers.
Yes, of course. Just keep in mind that you'll probably need to do more than just copy the pointers themselves. If the memory is dynamically allocated (as I assume it is for you to be asking this question) then you basically have to duplicate the logic for the constructor with the added concern of self assignment:

#include <cstring>
#include <iostream>
#include <ostream>

class jsw_string {
  char *_base;
public:
  jsw_string ( const char *init );
  jsw_string ( const jsw_string& rhs );
  ~jsw_string();

  jsw_string& operator= ( const jsw_string& rhs );

  friend std::ostream& operator<< ( std::ostream& out, const jsw_string& s );
private:
  char *_alloc_base ( const char *src );
};

jsw_string::jsw_string ( const char *init )
{
  _base = _alloc_base ( init );
}

jsw_string::jsw_string ( const jsw_string& rhs )
{
  _base = _alloc_base ( rhs._base );
}

jsw_string::~jsw_string()
{
  delete[] _base;
}

jsw_string& jsw_string::operator= ( const jsw_string& rhs )
{
  if ( this != &rhs ) {
    char *save = _alloc_base ( rhs._base );

    delete[] _base;
    _base = save;
  }

  return *this;
}

char *jsw_string::_alloc_base ( const char *src )
{
  char *s = new char[std::strlen ( src )];

  strcpy ( s, src );

  return s;
}

std::ostream& operator<< ( std::ostream& out, const jsw_string& s )
{
  return out<< s._base;
}

int main()
{
  jsw_string s = "this is a test";
  jsw_string r = s;

  std::cout<<"s = "<< s <<"\nr = "<< r <<'\n';

  s = "foo";

  std::cout<<"s = "<< s <<"\nr = "<< r <<'\n';
}
commented: Does the 's' stand for sarah or sally? +11

Thanks a lot for the help.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.