Ad

Friday, August 24, 2007

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:

No comments:

Post a Comment

You are free to comment anything, although you can comment as 'Anonymous' it is strongly recommended that you supply your name. Thank You.

Please don't use abusive language.