-
April 22nd, 2010, 06:07 AM
#1
Adapter
Hi please see the below code
Code:
#include<iostream>
using namespace std;
class OldRectangle{
int x1,x2,y1,y2;
public:
OldRectangle(int a,int b,int c,int d):x1(a),x2(b),y1(c),y2(d)
{
cout<<"Old Rectangle"<<endl;
}
void oldDraw()
{
cout<<"using old drawing method"<<endl;
}
};
class Rectangle{
public:
virtual void draw()=0;
};
class RectangleAdapter : public Rectangle, private OldRectangle{
public:
RectangleAdapter(int x,int y,int width, int height):
OldRectangle(x,y,x+width,y+height)
{
cout<<"Initialize the old rectanlge object through this new Rectangle adapter object"<<endl;
}
void draw()
{
oldDraw();
}
};
int main()
{
Rectangle *r= new RectangleAdapter(10,20,33,66);
r->draw();
return 0;
}
My question is why we need a RectangleAdapter class.
I can directly write in the main like
OldRectangle *ptr = new OldRectangle(10,20,10+33,20+66);
ptr->oldDraw();
this will do the same thing for me
Please clarify me.
Regards
-
April 22nd, 2010, 06:37 AM
#2
Re: Adapter
Originally Posted by Rajesh1978
My question is why we need a RectangleAdapter class.
I can directly write in the main like
OldRectangle *ptr = new OldRectangle(10,20,10+33,20+66);
ptr->oldDraw();
this will do the same thing for me
But you see, I have written this wonderful function with the prototype:
Code:
void beautifulDisplay(Rectangle* rectangle);
You want to use my function, but OldRectangle has nothing to do with Rectangle. You could derive a new class from Rectangle, but then you have to rewrite stuff that is already implemented in OldRectangle.
This is where RectangleAdapter comes in: it adapts your existing class' interface to the interface required by my existing function. You do not have to change your class; I do not have to change my function.
Last edited by laserlight; April 22nd, 2010 at 06:40 AM.
-
April 22nd, 2010, 07:42 AM
#3
Re: Adapter
Thanks Laserlight.
My doubt is clarified.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|