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;
}
r1is the object.r2is the pointer to the object.Pointer contains the address of the object. If the pointer has not initialized, it can have any value (that we don’t know). So, we initialize
0so that we know our pointer has value0. We can use that value to avoid double initializing or some memory error.When we are about to assign the object to the pointer, what we usually do is_