Operator loading

Hi guys!

I am learning c++ and trying to test different features of the language but facing problem in understanding operator overloading... The following code is executing as it should be... but I am learning OO features so for better understanding I am working on the following code and trying to understand
1. Constructors
2. Destructor
3. inline function
4. friend-declared member functions

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
  class Application{
public:
	int run();
};

int Application::run(){
	std::string str1("Hello ");
	std::string str2(str1);
	cout << str1 << str2 << endl;	// Shall print "Hello Hello "

	str2 = "my world!";
	cout << str1 << str2 << endl;	// Shall print "Hello my world!"

	std::string str3;
	cout << "Enter a name: ";
	cin >> str3;				// (... The user enters for instance "Pluto"...)
	str2 = str1 + str3;
	cout << str2 << endl;		// Shall print "Hello Pluto"
	str2 = "Goodbye " + str3;
	cout << str2 << endl;		// Shall print "Goodbye Pluto"
	cout << str1 << "and " << "Goodbye "
			<< (str1 == "Goodbye " ? "is " : "is not ") << "the same word!\n";
								// Shall print "Hello and Goodbye is not the same word!"
	return 0;
}


int main(){
	Application myApp;
	return myApp.run();
}


To understand the concept I am using the user defined class String..

so far my code is for the string class is

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class String{
       ...? // friend-declared member functions??
public:
       ...? // Constructors
       ~String();
      
       const String operator+(const String& s) const;
       const String operator+(const char* s) const;
       // More overloaded operators ...?

       const char* toC_str();
       int getLength();

private:
      char* _strPtr;
      int _strLen;
};


now I am trying to complete the class definition so that it can be executed properly... any kind of help will be appreciated

Best Regards,
So you are replacing std::string with your own implementation?

I'd first define operator+=:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class String{
public:
  String& operator+=(const String& s) const
  {
    int newStrLen = _strLen + s._strLen;
    char* newStr = new char[ newStrLen ];
    memcpy( newStr, _strPtr, _strLen );
    memcpy( newStr + _strPtr, s._strPtr, s._strLen );
    
    delete[] _strPtr;

    _strPtr = newStr;
    _strLen = newStrLen;
  }
}
@Stewbond - Think line 8 should be:
 
memcpy( newStr + _strLen, s._strPtr, s._strLen );

I rather think I would go with something like:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
    String& operator+=(const String& s) const
    {
        if (s.getLength())
        {
            const int length = _strLen + s._strLen ;
            char* buffer = new char[length+1]; // room for terminator

            std::copy(_strPtr, _strPtr + _strLen, buffer) ;
            std::copy(s._strPtr, s._strPtr + s._strLen+1, buffer + _strLen) ;

            delete [] _strPtr ;
            _strPtr = buffer ;
            _strLen = length ;
        }
    }


Of course, that makes the assumption that _strLen is the length of the string as opposed to being the number of chars allocated for the string and that all such strings are null terminated in the style of C strings.

The advantage of defining operator+= first is that other addition operations may be defined in terms of that operator (and, because of that, don't need to be actual members of the class.) For instance, we might define operator+ as follows:

1
2
3
4
String operator+(String a, const String& b) // notice that the first parameter is taken by value
{
    return a += b ;
}


The obvious place to start with a class is the constructors and assignment (and move) operations, not with operator overloads. Those should be correct before you move on.

As far as "friend declared member functions"... there is no such thing. Member functions have access to internals of the class - they don't need to be friends.
Last edited on
That works well. (and yeah, I messed up the memcpy() ).

You'll also want to define:
1
2
3
4
5
6
7
class String { friend std::ostream& operator<<(std::ostream& out, String& s); };
...
std::ostream& operator<<(std::ostream& out, String& s)
{
  out << s._strPtr; // Though you need to ensure _strPtr is null-terminated;
  return out;
}
Last edited on
Hi guys!

Thanks for your time and effort but i can't run the program there are too many problems.

I have two class and want to execute the main class properly.

1. main class (.cpp)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
int main()
{
	string str1("Hello");
	string str2(str1);
	cout << str1 << str2 << endl;
	
	str2 = "my world!";
	cout << str1 <, str2 << endl;

	string str3;
	cout << "Enter a name: ";
	cin >> str3;

	str2 = str1 + str3;
	cout << str2 << endl;
	str2 = "Goodbye " + str3;
	cout << str2 << endl;
	cout << str1 << "and" << "Goodbye"
		<< (str1 == "Goodbye " ? "is " : "is not ") << " the same world!\n";
	return 0;
	
}

2. String class (.h)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class String
{
	           ...? // friend-declared member functions??
public:
	           ...? // Constructors
	           ~String();
	            
	           const String operator+(const String& s) const;
                  const String operator+(const char* s) const;
	           // More overloaded operators ...?
	      
	           const char* toC_str();
                   int getLength();
	      
private:
	          char* _strPtr;
	          int _strLen;
};
main.cpp line 8: second output operator should be << not <,

Note that main.cpp is using std::string, not your String class.

You say "I have two class", but I don't see any user defined classes used in main.



Topic archived. No new replies allowed.