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?
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;
}
CRectangle r1, *r2; r2= new CRectangle;
r1
is the object. r2
is the pointer to the object.
CRectangle *r2 = 0;
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 0
so that we know our pointer has value 0
. 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_
if (r2 == 0)
r2 = new CRectangle;
else
std::cout << "Pointer is not empty or invalid" << std::endl;
CRectangle r1, *r2;
r2= new CRectangle;
This code declares a CRectangle
object ( r1
), and a pointer to a CRectangle
object, which doesn't yet point to anything ( r2
). Both variables are allocated on the stack.
The second line allocates memory for a new CRectangle
object (from the heap), calls any constructor for that class, and then returns the address and assigns it to r2
. So r2
then points to a CRectangle
object.
Setting r2
to 0 or NULL
is simply a standard way to indicate that the pointer doesn't actually point to anything.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.