Docsity

Other Binary Operators-Object Oriented Programming-Lecture Slides, Slides of Object Oriented Programming

Partial preview of the text

Download Other Binary Operators-Object Oriented Programming-Lecture Slides and more Slides Object Oriented Programming in PDF only on Docsity!

Object-Oriented Programming

(OOP)

Lecture No. 20

Other Binary operators^ ►We have seen the following string class till now:^ class

String{private:char^ *^ bufferPtr;

int^ size;

public:String();String(char

*^ ptr); void^ SetString(char

*^ ptr);

const^

char^ *

GetString(); ...};

Other Binary Operators^ ►What if we want to change the stringfrom “

Ping ” to “

Pong

”??^ {ONLY 1

character to be changed…} ►Possible solution:^ Call:

str2.SetString(“Pong”); This will delete the current buffer andallocate a new one

Other Binary Operators^ ►Or, we can add a function whichchanges a character at nth location^ class String{

...public:void SetChar(char c, int pos);...

Other Binary Operators^ ►Now we can efficiently change asingle character:^ String

str1(“Ping”); str1.SetChar(‘o’,

// str1 is now changed to “

Pong

Subscript Operator ►An elegant solution: ►Overloading the subscript “

[]”

operator

Subscript Operator class String{...public:char & operator;...};

Subscript Operator char & String::operator[](

int pos){

assert(pos>0 && pos<=size);return stringPtr[pos-1];}

Subscript Operator ►Output:^ PingPong

Overloading

►Must be a member function ►Any number of parameters can be specified ►Any return type can be specified ►Operator()

can perform any generic

operation

Function Operator char & String::operator()

(int pos){

assert(pos>0 && pos<=size);return bufferPtr[pos-1];}

Subscript Operator int main(){String s1(“Ping”);char g = s1(2);

// g = ‘i’ s1(2) = ‘o’;cout << g << “\n”;cout << str.GetString();return 0;

Function Operator class String{... public:String operator()(int, int);... };

Function Operator String^ String::operator()(int

index,

int^ subLength){ assert(index>

&&^ index+subLength-1<=size); char^ *

ptr^ =

new^ char[subLength+1]; for^ (int

i=0;^

i^ <^ subLength;

++i)

ptr[i]

=^ bufferPtr[i+index-1]; ptr[subLength]

=^ ‘\0’; String

str(ptr); delete

[]^ ptr; return

str;