Professional Documents
Culture Documents
Operator Overloading I: by Jitendra Singh Chauhan (Project Engineer) CDAC Noida
Operator Overloading I: by Jitendra Singh Chauhan (Project Engineer) CDAC Noida
// part of main
{
Complex c1(1, 3);
Complex c2 (3, 5);
Complex c3 = c1 + c2;
}
+ operator will work for Complex objects if operator +
is overloaded for class Complex.
statement 3 can be resolved as
c3 = c1.operator + (c2) // as a member function or
c3 = operator + (c1,c2) // as a friend function
// part of main
{
Complex c1(1, 3);
Complex c2 ;
c2 = c1++;
c2 = ++c1; // c2 = c1.operator ++()
}
++ operator will work for Complex objects if
operator ++ is overloaded for class Complex.
++ as a PreIncrement Operator
Complex & Complex :: operator++( ) // Unary operator
// hidden parameter is this pointer
{
++m_real; //or m_real++;
++m_imag; // or m_imag++;
return(*this);
}
++ as a PostIncrement Operator
Complex Complex :: operator++( int ) // Unary operator
// hidden parameter is this pointer
// int is a dummy parameter
{
Complex Temp = *this ;
m_real++ ;
m_imag++ ;
return(Temp);
}
if(this == &s)
return(*this); // step 4
{
else
m_len = s.m_len;
delete [ ] m_pbuff; // step 1
m_pbuff = new char [m_len + 1]; // step 2
strcpy(m_pbuff,s.m_pbuff); // step 3
return (*this); }
}
class A class B {
{ { A a1;
A (B&); operator A(); B b1;
} } a1 = b1;
}
Whether constructor or conversion function should be
used depends upon which class code is available for
programmer for modifications.
by jitendra singh chauhan(Project Engineer)CDAC Noida
Try this
Construct a class to represent array of integers
Write default value constructor, parameterized constructor for
the class say intArray
Write destructor for the same
overload subscript operator.
Confirm that following operations are allowed
intArray arr1(10);
arr1[0] = 5;
arr1[1] = 7;
…
int x = arr1 [6];