Showing posts with label operator overloading. Show all posts
Showing posts with label operator overloading. Show all posts

Class initialisation and constructors

There is often lots of confusion with regards to class initialisation. People may forget to take care while using default constructors and copy constructors. Here is a simple example that tries to explain lots of concepts.





//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
//This program gives an example of constructors and initialisations

#include<iostream>

using namespace
std;

//Example of a class
class someClass1
{

public
:
//implicit default constructor
int x;
int
*y;
};


//Example of a class with constructor
class someClass2
{

public
:
someClass2(const someClass2& xyz)
{

cout<<"** copy constructor called"<<endl;
x = xyz.x;
y = new int(*xyz.y);
}

//default constructor will have to be explicitly defined
someClass2() {};
//overloading operator '='
const someClass2& operator = (const someClass2& xyz)
{

cout<<"** operator '=' called"<<endl;
x = xyz.x;
y = new int(*xyz.y);
return
*this;
}

int
x;
int
*y;
};


int
main()
{

someClass1 a; //Default initialisation
a.x = 1234;
a.y = new int(6789);

cout<<"someClass1: a.x = "<<a.x<<" a.y( " <<a.y<< " ) = "<<*(a.y)<<endl;

someClass1 b = a; //Copy Initialisation

cout<<"someClass1: b.x = "<<b.x<<" b.y( " <<b.y<< " ) = "<<*(b.y)<<endl;

someClass1 c(a); //Direct Initialisation

cout<<"someClass1: c.x = "<<c.x<<" c.y( " <<c.y<< " ) = "<<*(c.y)<<endl;

//Calling default constructor
someClass2 aa;
aa.x = 2468;
aa.y = new int(3579);

cout<<"someClass2: aa.x = "<<aa.x<<" aa.y( " <<aa.y<< " ) = "<<*(aa.y)<<endl;

//calling copy constructor
someClass2 bb = aa; //Copy Initialisation - note copy constructor will be called

cout<<"someClass2: bb.x = "<<bb.x<<" bb.y( " <<bb.y<< " ) = "<<*(bb.y)<<endl;

//calling copy constructor
someClass2 cc(aa); //Direct Initialisation - note copy constructor called in this case as well

cout<<"someClass2: cc.x = "<<cc.x<<" cc.y( " <<cc.y<< " ) = "<<*(cc.y)<<endl;

someClass2 dd;
//calling operator =
dd = aa;

cout<<"someClass2: dd.x = "<<dd.x<<" dd.y( " <<dd.y<< " ) = "<<*(dd.y)<<endl;

return
0;
}







The output is as follows:

There are certain things worth noting in the above example:
  • In case of someClass1, since only the default constructor is used, the same pointer is used for y in all the cases. This can cause serious problems in the code if one of the classes delete the memory pointed by y for class someClass1. This problem is not present in someClass2
  • If any constructor is defined, it becomes necessary to define the default constructor. You can make sure that nobody uses default constructor in case of someClass2 by making it private (I havent done that because I wanted to show operator =)
  • As you can see in case of variable cc, copy constructor would always be called instead of operator =.
  • operator = would only be called in case of assignment. This is a common mistake.
  • In the code above, cc(aa) is better than using bb = aa even though the results are the same. The main advantage being that it will avoid confusion with operator '=' if its overloaded for a novice and the constructor can be overloaded to take more than one input in future.

Example of 'functors'

What are 'functors?'

Depending on what you prefer to read, there are many definitions and explanations of Functors.

From the function pointer tutorial:

Functors are functions with a state. In C++ you can realize them as a class with one or more private members to store the state and with an overloaded operator () to execute the function. Functors can encapsulate C and C++ function pointers employing the concepts templates and polymorphism. You can build up a list of pointers to member functions of arbitrary classes and call them all through the same interface without bothering about their class or the need of a pointer to an instance. All the functions just have got to have the same return-type and calling parameters. Sometimes functors are also known as closures. You can also use functors to implement callbacks.

From StackOverflow:
  • A functor is pretty much just a class which defines the operator(). That makes it "look like" a function.
  • Another advantage to a functor over a pointer to a function is that the call can be inlined in more cases.
  • You can use boost::function, to create functors from functions and methods
Here is a simple example of functors that I have created using mishmash from various places:



//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
//Program to demonstrate the use of functors

#include<iostream>

using namespace
std;

class
someClass
{

public
:
someClass(int x) : someVariable(x) {}
int
operator()(int y) {return (someVariable + y);}
int
internalStateValue(){return someVariable;}

private
:
int
someVariable;
};


int
main()
{

someClass class1(50);
someClass class2(75);

cout<<"Class1 state variable value is : "<<class1.internalStateValue()<<endl;
cout<<"Class2 state variable value is : "<<class2.internalStateValue()<<endl;

int
test1 = class1(22);
cout<<"Test 1 value is : "<< test1<<endl;
int
test2 = class2(22);
cout<<"Test 2 value is : "<< test2<<endl;

cout<<"Class1 final state variable value is : "<<class1.internalStateValue()<<endl;
cout<<"Class2 final state variable value is : "<<class2.internalStateValue()<<endl;

return
0;
}





The output is as follows:

A look at Smart Pointers

There is lot of confucion, misconceptions and misunderstanding regarding smart pointers. After looking at various books and tutorials, i got quite confused till I managed to figure out what they exactly are:

Smart pointers are objects that look and feel like pointers, but are smarter.

To look and feel like pointers, smart pointers need to have the same interface that pointers do: they need to support pointer operations like dereferencing (operator *) and indirection (operator ->). An object that looks and feels like something else is called a proxy object, or just proxy.

To be smarter than regular pointers, smart pointers need to do things that regular pointers don't. What could these things be? Probably the most common bugs in C++ (and C) are related to pointers and memory management: dangling pointers, memory leaks, allocation failures and other joys. Having a smart pointer take care of these things.

The simplest example of a smart pointer is auto_ptr, which is included in the standard C++ library. You can find it in the header , or take a look at Scott Meyers' auto_ptr implementation. Here is part of auto_ptr's implementation, to illustrate what it does:

template <class T> class auto_ptr
{

T* ptr;
public
:
explicit
auto_ptr(T* p = 0) : ptr(p) {}
~
auto_ptr() {delete ptr;}
T& operator*() {return *ptr;}
T* operator->() {return ptr;}
// ...
};

As you can see, auto_ptr is a simple wrapper around a regular pointer. It forwards all meaningful operations to this pointer (dereferencing and indirection). Its smartness in the destructor: the destructor takes care of deleting the pointer.

Lets look at a proper example:

#include<iostream>
#include<memory>


using namespace
std;

class
A
{

public
:
int
*data;
string name;
A(string n): name(n)
{

cout<<"Constructor of A = "<<name.c_str()<<" called "<<endl;
data = new(int);
};

A(string n, int x): name(n)
{

cout<<"Overloaded Constructor of A = "<<name.c_str()<<" called "<<endl;
data = new(int);
*
data = x;
};
~
A()
{

cout<<"Destructor of A = "<<name.c_str()<<" called "<<endl;
delete
(data);
data = this->data;
data = NULL;
}

A* operator ->() { return this;};
};


void
someFunc()
{

auto_ptr<A> a1(new A("a1"));
cout<<"Enter a number and press enter: ";
cin >> (*a1->data);
cout << "a1->data = "<<*a1->data<<endl;

A a2("a2",25);
A *a3 = new A("a3");
}


int
main()
{

cout<<"Before SomeFunc()"<<endl;
someFunc();
cout<<"After SomeFunc()"<<endl;
return
0;
}
The output is as follows:


As you have probably noticed, the instance a3 is never deleted and will cause memory leaks. Using smart pointer would automatically delete the instance a3 and the memory associated with it.

You can read Smart Pointers in much more detail at the References below.

References:
http://ootips.org/yonat/4dev/smart-pointers.html
http://www.geekpedia.com/tutorial47_Smart-Pointers---Part-1.html
http://www.geekpedia.com/tutorial59_Smart-Pointers---Part-II.html

Simulating FIFO behaviour with priority queues for equal priorities

In priority queue, the C++ specifications does not define the behaviour of the algorithms when equal-priority items are involved. It is assumed that the ordering is not important in case of a priority queue as long as the same priority items are in correct order as compared to other priorities. For a programmer though this can be important as he expects FIFO ordering for same priority items. To overcome the problem I mentioned in earlier program, we can add another item to get correct FIFO ordering for same priority items.

This is just one approach and there may be other approaches. Also notice that I have used a local variable which requires the order to be input. You can also use the static variable approach for this.


//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
//Example of slightly advanced priority queue making sure that
//along with priorities, queue functionality of FIFO is maintained
#include <iostream>
#include <string>
#include <vector>
#include <queue>

using namespace
std;

class
PrioritizedWord
{

private
:
int
m_prio;
string m_word;
int
m_order; //To set FIFO operation

public
:
explicit
PrioritizedWord()
{ }

explicit
PrioritizedWord(const std::string& word, const int priority = 0, const int order = 0):
m_word(word), m_prio(priority), m_order(order)
{ }

//Operator overloading for priority comparison
const bool operator <(const PrioritizedWord& pW) const
{

if
(m_prio == pW.m_prio)
return
(m_order > pW.m_order);
else
return
(m_prio < pW.m_prio);
}

//Operator overloading to print output
friend ostream& operator <<(ostream& out, const PrioritizedWord& pW)
{

out<<pW.m_word;
return
out;
}

int
getPrio(void)
{
return m_prio;}
string getWord(void)
{
return m_word;}
};


int
main()
{

priority_queue<PrioritizedWord> zahidQueue;

//Note the final order will not be the same as the specs do not
//define behaviour in case two numbers with equal priority exist
zahidQueue.push(PrioritizedWord("First", 23, 1));
zahidQueue.push(PrioritizedWord("Second", 23, 2));
zahidQueue.push(PrioritizedWord("Third", 23, 3));
zahidQueue.push(PrioritizedWord("Fourth", 51, 4));
zahidQueue.push(PrioritizedWord("Fifth", -1, 5));

cout<<"\n\nZahid Queue elements :"<<endl;
while
(!zahidQueue.empty())
{

cout<<zahidQueue.top()<<" "<<endl;
zahidQueue.pop();
}


return
0;
}



The output is as follows:

Simple example of Priority Queue

Here is a simple example of priority queue:



//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy

//Example showing how simple priority queues work using C++

#include <iostream>

#include <string>

#include <vector>

#include <queue>



using namespace
std;



class
PrioritizedWord

{


private
:

int
m_prio;

string m_word;



public
:

explicit
PrioritizedWord()

{ }


explicit
PrioritizedWord(const std::string& word, const int priority = 0):

m_word(word), m_prio(priority)

{ }


//Operator overloading for priority comparison

const bool operator <(const PrioritizedWord& pW) const

{


return
(m_prio < pW.m_prio);

}


//Operator overloading to print output

friend ostream& operator <<(ostream& out, const PrioritizedWord& pW)

{


out<<pW.m_word;

return
out;

}


int
getPrio(void)

{
return m_prio;}

string getWord(void)

{
return m_word;}

};




int
main()

{


int
somenum = 2;

while
(somenum > 0)

{


priority_queue<PrioritizedWord> wordQueue, zahidQueue, *temp=NULL;

//Word Queue first time, Zahid Queue second time

if(somenum%2==0)

{


temp = &wordQueue;

}


else


{


temp = &zahidQueue;

}




//Note the final order will not be the same as the specs do not

//define behaviour in case two numbers with equal priority exist

temp->push(PrioritizedWord("First", 23));

temp->push(PrioritizedWord("Second", 23));

temp->push(PrioritizedWord("Third", 23));

temp->push(PrioritizedWord("Fourth", 51));

temp->push(PrioritizedWord("Fifth", -1));



cout<<"\n\nWord Queue elements (All elements lost):"<<endl;

while
(!wordQueue.empty())

{


cout<<wordQueue.top()<<" "<<endl;

wordQueue.pop();

}




cout<<"\n\nZahid Queue elements (Elements preserved):"<<endl;

if
(!zahidQueue.empty())

{


priority_queue<PrioritizedWord> tempQueue;

while
(!zahidQueue.empty())

{


PrioritizedWord &temppW = zahidQueue.top();

cout<<temppW<<" "<<endl;

tempQueue.push(PrioritizedWord(temppW.getWord(), temppW.getPrio()));

zahidQueue.pop();

}


while
(!tempQueue.empty())

{


PrioritizedWord &temppW = tempQueue.top();

zahidQueue.push(PrioritizedWord(temppW.getWord(), temppW.getPrio()));

tempQueue.pop();

}

}




cout<<"\n\nZahid Queue - Removing an element and leaving the rest"<<endl;

{


priority_queue<PrioritizedWord> tempQueue;

while
(!zahidQueue.empty())

{


PrioritizedWord &temppW = zahidQueue.top();



if
(temppW.getWord() != "Second")

{


tempQueue.push(PrioritizedWord(temppW.getWord(), temppW.getPrio()));

zahidQueue.pop();

}


else


{


zahidQueue.pop();

break
;

}

}


while
(!tempQueue.empty())

{


PrioritizedWord &temppW = tempQueue.top();

zahidQueue.push(PrioritizedWord(temppW.getWord(), temppW.getPrio()));

tempQueue.pop();

}

}




cout<<"\n\nZahid Queue elements after removal of element"<<endl;

while
(!zahidQueue.empty())

{


cout<<zahidQueue.top()<<" "<<endl;

zahidQueue.pop();

}


somenum--;

}




return
0;

}


The output is as follows:

Overloading the Parenthesis () Operator

First, I want to apologize to my readers for not being able to post lately,
partly due to me being very busy these days;-)


As we all know, there are certain ways by which we can pass data to objects
(of class). We can pass values during the time of construction as below:


  class-name ob-name(values);

Or we may define a member function to accept data which can be called as below:


  class-name ob-name;
ob-name.set(values);

Where set is the member function of the class.


But actually there is one more way to do so, yeah you guessed it right!, by
overloading the parenthesis () operator.


Parenthesis () operator like other operators is overloaded with the following
prototype:


  ret-type operator()(arg1, arg2,...);


It is a unary operator hence the only argument passed to this function (implicitly)
is this pointer. The argument list may contain any number of arguments as you
wish to pass.


The following example program illustrates the overloading of parenthesis ()
operator in C++.



// Overloading Parenthesis ()
// Operator
#include <iostream.h>

class myclass
{
int a,b;

public:
myclass(){}
myclass(int,int);
myclass operator()(int,int);
void show();
};

// ------------------------
// --- MEMBER FUNCTIONS ---
myclass::myclass(int x, int y)
{
a=x;
b=y;
}

myclass myclass::operator()(int x, int y)
{
a=x;
b=y;

return *this;
}

void myclass::show()
{
cout<<a<<endl<<b<<endl;
}
// --- MEMBER FUNCTIONS ---
// ------------------------

void main()
{
myclass ob1(10,20);
myclass ob2;

ob1.show();

// it's a nice way to pass
// values, otherwise we
// would have to define and
// call a member/friend function
// to do so
ob2(100,200);
ob2.show();
}


Related Articles:


Overloading [] Operator II

In the previous article Overloading
[] Operator
, we overloaded the [] operator in a class to access data
within the class by indexing method.


The operator [] function was defined as below:


  int myclass::operator[](int index)
{
// if not out of bound
if(index<num)
return a[index];
}

As you can see, the above operator
function
is returning values, hence it could only be used on the right
hand side of a statement. It’s a limitation!


You very well know that a statement like below is very common with respect
to arrays:


a[1]=10;


But as I said, the way we overloaded the [] operator, statement like the one
above is not possible. The good news is, it is very easy to achieve this.


For this we need to overload the [] operator like this:


  int &myclass::operator[](int index)
{
// if not out of bound
if(index<num)
return a[index];
}

By returning a reference
to the particular element, it is possible to use the index expression on the
left hand side of the statement too.


The following program illustrates this:



// Example Program illustrating
// the overloading of [] operator
// ----
// now the index expression can be
// used on the left side too
#include <iostream.h>

class myclass
{
// stores the number of element
int num;
// stores the elements
int a[10];

public:
myclass(int num);

int &operator[](int);
};

// takes the number of element
// to be entered.(<=10)
myclass::myclass(int n)
{
num=n;
for(int i=0;i<num;i++)
{
cout<<"Enter value for element "<<i+1<<":";
cin>>a[i];
}
}

// returns a reference
int &myclass::operator[](int index)
{
// if not out of bound
if(index<num)
return a[index];
}

void main()
{
myclass a(2);

cout<<a[0]<<endl;
cout<<a[1]<<endl;

// indexing expression on the
// left-hand side

a[1]=21;
cout<<a[1];
}


Related Articles:


Overloading [] Operator

Have a look at the following code fragment:


  myclass a(3);

cout<<a[0];

Doesn’t it look awkward!


Yes it does, because we have overloaded he [] operator and given it some special
meaning.


In C++, it is possible to overload the [] operator
and give it a different meaning
rather then the usual object indexing.


The general form for overloading [] operator is:


  ret-type operator[](int);

It is considered a binary operator hence when declared as a member, it accepts
one explicit argument (usually int).


Although you are free to accept any type of argument but sticking to the original
concept of indexing, it would always be an integer.


ob[i];


When the compiler encounters the above expression (with the [] operator overloaded)
the [] operator
function
is called as below:


ob.operator[] (1)


The argument ‘1’ is passed explicitly while ‘ob’ is
passed implicitly using the ‘this’
pointer.


Enough discussion, now lets get on to some action!


Below is the example program illustrating the overloading of [] operator:



// Example Program illustrating
// the overloading of [] operator
#include <iostream.h>

class myclass
{
// stores the number of element
int num;
// stores the elements
int a[10];

public:
myclass(int num);

int operator[](int);
};

// takes the number of element
// wished to be entered.(<=10)
myclass::myclass(int n)
{
num=n;
for(int i=0;i<num;i++)
{
cout<<"Enter value for element "<<i+1<<":";
cin>>a[i];
}
}

int myclass::operator[](int index)
{
// if not out of bound
if(index<num)
return a[index];

// else
return NULL;
}

void main()
{
myclass a(3);

cout<<a[0]<<endl;
cout<<a[2]<<endl;

// out of bound
cout<<a[3]<<endl;
}


Related Articles:


Adding Flexibility to Operators while Overloading them

  class_name class_name::operator+(int x)
{
class_name temp;

temp.a = a + x;
temp.b = b + x;

return temp;
}


With reference to the above operator
function
and supposing that ‘ob’ is an object of the class
to which this function belongs; Is the statement below legal:


ob2 = ob1 + 100;


Yes, but what about the following statement:


ob2 = 100 + ob1;


Surely this won’t work!


100 is an integer constant and has no ‘+’ operator that could add
it with user-defined types (object ‘ob’).


This certainly is a shortcoming, since often we don’t really care which
operand is where (as in addition and multiplication) and we order the operands
as necessary (as in subtraction and division).


To overcome this we can overload two-two versions of these operators
as friend
, one for ‘integer + object’ type and the other
for ‘object + integer’ type.


So, for example for addition we have to overload the ‘+’ operator
twice as below:


  friend class_name operator+(class_name,int);
friend class_name operator+(int,class_name);

Similarly we have to overload other operators.


The program below illustrates this concept:



// Program to illustrate
// the overloading of
// flexible addition
// and subtraction
// operators
#include <iostream.h>

class myclass
{
int a;
int b;

public:
myclass(){}
myclass(int x,int y){a=x;b=y;}
void show()
{
cout<<a<<endl<<b<<endl;
}

// object + int form
friend myclass operator+(myclass,int);
friend myclass operator-(myclass,int);

// int + object form
friend myclass operator+(int,myclass);
friend myclass operator-(int,myclass);
};

myclass operator+(myclass ob,int x)
{
myclass temp;

temp.a = ob.a + x;
temp.b = ob.b + x;

return temp;
}

myclass operator-(myclass ob, int x)
{
myclass temp;

temp.a = ob.a - x;
temp.b = ob.b - x;

return temp;
}

myclass operator+(int x, myclass ob)
{
// does the same thing
// because in addition
// it doesn't matters
// which operand is where
myclass temp;

temp.a = x + ob.a;
temp.b = x + ob.b;

return temp;
}

myclass operator-(int x, myclass ob)
{
myclass temp;

temp.a = x - ob.a;
temp.b = x - ob.b;

return temp;
}

void main()
{
myclass a(10,20);
myclass b(100,200);

a=a + 10;
a.show();

b=100 + b;
b.show();
}


Related Articles:


Using Friends to Overload all the Overloaded Arithmetic Operators

In the article Class
with all the Overloaded Arithmetic Operators
, we overloaded (almost)
all the arithmetic operators in one program, similarly in this article we’ll
be overloading them once again but now using friend functions.


We have already overloaded similar operators before (using friend
functions
), so you won’t be having any troubles in understanding
the program below:



// Program that Overloads
// all the arithmetic operators
// using friend functions
#include <iostream.h>

class myclass
{
int a;
int b;

public:
myclass(){}
myclass(int x,int y){a=x;b=y;}
void show()
{
cout<<a<<endl<<b<<endl;
}

// declared as friend
friend myclass operator+=(myclass&, myclass);
friend myclass operator-=(myclass&, myclass);

friend myclass operator++(myclass&);
friend myclass operator--(myclass&);

friend myclass operator++(myclass&, int);
friend myclass operator--(myclass&, int);

friend myclass operator+(myclass,myclass);
friend myclass operator-(myclass,myclass);

friend myclass operator/(myclass, myclass);
friend myclass operator*(myclass, myclass);
friend myclass operator%(myclass, myclass);
};

myclass operator+=(myclass &ob1, myclass ob2 )
{
ob1.a+=ob2.a;
ob1.b+=ob2.b;

return ob1;
}

myclass operator-=(myclass &ob1, myclass ob2 )
{
ob1.a-=ob2.a;
ob1.b-=ob2.b;

return ob1;
}

myclass operator++(myclass &ob)
{
ob.a++;
ob.b++;

return ob;
}

myclass operator--(myclass &ob)
{
ob.a--;
ob.b--;

return ob;
}

myclass operator++(myclass &ob, int x)
{
myclass temp;
temp=ob;

ob.a++;
ob.b++;

return temp;
}

myclass operator--(myclass &ob, int x)
{
myclass temp;
temp=ob;

ob.a--;
ob.b--;

return temp;
}

myclass operator+(myclass ob1,myclass ob2)
{
myclass temp;

temp.a = ob1.a + ob2.a;
temp.b = ob1.b + ob2.b;

return temp;
}

myclass operator-(myclass ob1,myclass ob2)
{
myclass temp;

temp.a = ob1.a - ob2.a;
temp.b = ob1.b - ob2.b;

return temp;
}

myclass operator/(myclass ob1,myclass ob2)
{
myclass temp;

temp.a = ob1.a / ob2.a;
temp.b = ob1.b / ob2.b;

return temp;
}

myclass operator*(myclass ob1,myclass ob2)
{
myclass temp;

temp.a = ob1.a * ob2.a;
temp.b = ob1.b * ob2.b;

return temp;
}

myclass operator%(myclass ob1,myclass ob2)
{
myclass temp;

temp.a = ob1.a % ob2.a;
temp.b = ob1.b % ob2.b;

return temp;
}

void main()
{
myclass a(10,20);
myclass b(100,200);

a+=b;
a.show();

a++;
a.show();

a=a*a;
a.show();

a=a%b;
a.show();
}


Related Articles:


Problems on Operator Overloading II

This is the second part of the artcile Problems
on Operator Overloading I
.


Problem #4: What would be the
output of the following code:



1 // Problem #4:
2 // Problem related to
3 // Operators Overloading
4 #include <iostream.h>
5
6 class myclass
7 {
8 int a;
9 int b;
10
11 public:
12 myclass(){}
13 myclass(int x,int y){a=x;b=y;}
14 void show()
15 {
16 cout<<a<<endl<<b<<endl;
17 }
18
19 friend myclass operator++(myclass);
20 };
21
22 myclass operator++(myclass ob)
23 {
24 ob.a++;
25 ob.b++;
26
27 return ob;
28 }
29
30 void main()
31 {
32 myclass a(10,20);
33
34 ++a;
35
36 a.show();
37 }

Problem #5: What would be the
output of the following code:



1 // Problem #5:
2 // Problem related to
3 // Operators Overloading
4 #include <iostream.h>
5
6 class myclass
7 {
8 int a;
9 int b;
10
11 public:
12 myclass(){}
13 myclass(int x,int y){a=x;b=y;}
14 void show()
15 {
16 cout<<a<<endl<<b<<endl;
17 }
18
19 friend myclass operator+=(myclass,
20
21 myclass);
22 };
23
24 myclass operator+=(myclass ob1, myclass ob2 )
25 {
26 ob1.a+=ob2.a;
27 ob1.b+=ob2.b;
28
29 return ob1;
30 }
31
32 void main()
33 {
34 myclass a(10,20);
35 myclass b(100,200);
36
37 a+=b;
38 b+=a;
39
40 a.show();
41 b.show();
42 }

Problem #6: Is there any error(s)
in the following code:



1 // Problem #6:
2 // Problem related to
3 // Operators Overloading
4 #include <iostream.h>
5
6 class myclass
7 {
8 int a;
9 int b;
10
11 public:
12 myclass(){}
13 myclass(int x,int y){a=x;b=y;}
14 void show()
15 {
16 cout<<a<<endl<<b<<endl;
17 }
18
19 myclass operator++(myclass &);
20 };
21
22 myclass myclass::operator++(myclass &ob)
23 {
24 ob.a++;
25 ob.b++;
26
27 return ob;
28 }
29
30 void main()
31 {
32 myclass a(10,20);
33
34 ++a;
35
36 a.show();
37 }

ANSWERS:




  1. 10 20, Refer to this
    article
    .




  2. 10 20 100 200. Same reason as above.



  3. Has errors inline no. 19, '++' is a unary operator and hence doesn't need
    any other argument.


Related Articles:


Problems on Operator Overloading I

Here I'm listing some problems related to Operator Overloading to spice up
the discussion a bit. This is a TWO part series so read the next
article
after solving each of the problems listed here.



Problems
on Operator Overloading I


Problems
on Operator Overloading II



Problem #1: Point out the error(s)
if any in the following code:



1 // Problem #1:
2 // Problem related to
3 // Operators Overloading
4 #include <iostream.h>
5
6 class myclass
7 {
8 int a;
9 int b;
10
11 public:
12 myclass(){}
13 myclass(int x,int y){a=x;b=y;}
14 void show()
15 {
16 cout<<a<<endl<<b<<endl;
17 }
18
19 myclass operator+(int);
20 };
21
22 myclass myclass::operator+(int x)
23 {
24 myclass temp;
25
26 temp.a=a + x;
27 temp.b=b + x;
28
29 return temp;
30 }
31
32 void main()
33 {
34 myclass a(10,20);
35
36 a=a+10;
37 a.show();
38 }

Problem #2: Point out the error(s)
if any in the following code:



1 // Problem #2:
2 // Problem related to
3 // Operators Overloading
4 #include <iostream.h>
5
6 class myclass
7 {
8 int a;
9 int b;
10
11 public:
12 myclass(){}
13 myclass(int x,int y){a=x;b=y;}
14 void show()
15 {
16 cout<<a<<endl<<b<<endl;
17 }
18
19 int operator=(int);
20 };
21
22 int myclass::operator=(int x)
23 {
24 a=x;
25 b=x;
26
27 return x;
28 }
29
30 void main()
31 {
32 myclass a(10,20);
33 myclass b,c;
34
35 c=b=a;
36
37 c.show();
38 }

Problem #3: Point out the error(s)
if any in the following code:



1 // Problem #6:
2 // Problem related to
3 // Operators Overloading
4 #include <iostream.h>
5
6 class myclass
7 {
8 int a;
9 int b;
10
11 public:
12 myclass(){}
13 myclass(int x,int y){a=x;b=y;}
14 void show()
15 {
16 cout<<a<<endl<<b<<endl;
17 }
18
19 myclass operator++();
20 };
21
22 myclass myclass::operator++()
23 {
24 a++;
25 b++;
26
27 return this;
28 }
29
30 void main()
31 {
32 myclass a(10,20);
33
34 ++a;
35
36 a.show();
37 }

ANSWERS:




  1. No Errors




  2. No Errors



  3. We need to return the object and not the pointer
    (this)
    . The statement should have been, return *this;


Related Articles:


Overloading the Short-Hand Operators (+= and -=) using Friend Functions

In this article we’re going to overload the shorthand
addition (+=) and subtraction (-=) operators
using friend
functions.


As you can observe in the program below, the operator functions are taking
the first argument (operand) as a reference
(call by reference). This is due the fact that these operators need to alter
the data of the actual operand itself.


This is similar to the case of increment/decrement
operators
(click for detailed information).



// Overloading the shorthand
// += and -= operators using
// friend functions
#include <iostream.h>

class myclass
{
int a;
int b;

public:
myclass(){}
myclass(int x,int y){a=x;b=y;}
void show()
{
cout<<a<<endl<<b<<endl;
}

// declared as friend
friend myclass operator+=(myclass&, myclass);
friend myclass operator-=(myclass&, myclass);
};


myclass operator+=(myclass &ob1, myclass ob2 )
{
// data of the first operand
// are to be changed, so accepting
// it as a reference
ob1.a+=ob2.a;
ob1.b+=ob2.b;

return ob1;
}

myclass operator-=(myclass &ob1, myclass ob2 )
{
ob1.a-=ob2.a;
ob1.b-=ob2.b;

return ob1;
}

void main()
{
myclass a(10,20);
myclass b(100,200);

a+=b;
b+=a;

a.show();
b.show();
}


Related Articles:


Check out this stream