I saw the below code in Stackoverflow.com
.
I was looking for the same code, bacuse I have a doubt.
If we will see the below code
CRectangle r1, *r2;
r2= new CRectangle;
1. Why are we doing new CRectangle
? What actually we are trying to do?
- One of colleague told me,
when we write the code we make,
CRectangle *r2 = 0;
,
Then we initialize
with some other value or address. I really got confused. Please help me.
using namespace std;
class CRectangle
{
int width, height;
public:
void set_values (int, int);
int area (void) {return (width * height);
}
};
void CRectangle::set_values (int a, int b)
{
width = a;
height = b;
}
int main ()
{
CRectangle r1, *r2;
r2= new CRectangle;
r1.set_values (1,2);
r2->set_values (3,4);
cout << "r1.area(): " << r1.area() << endl;
cout << "r2->area(): " << r2->area() << endl;
cout << "(*r2).area(): " << (*r2).area() << endl;
delete r2;
return 0;
}