-1

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?

  1. 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; 
} 
Rasmi Ranjan Nayak
  • 11,510
  • 29
  • 82
  • 122

3 Answers3

1

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;
Lwin Htoo Ko
  • 2,326
  • 4
  • 26
  • 38
  • :- I think your explanation really answers my doubt. I was bit confused with `r2 = new CRectangle` but @JonathanWood answered the same. Thanks A Lot – Rasmi Ranjan Nayak Aug 22 '12 at 06:35
1

In your example r1 has type of CRectangle class, but r2 has type of pointer to CRectangle class. The pointer is just address in global memory (heap). In order to allocate and mark memory as CRectangle object we need use new.

Please, read the details in books

Community
  • 1
  • 1
fasked
  • 3,555
  • 1
  • 19
  • 36
1
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.

Jonathan Wood
  • 65,341
  • 71
  • 269
  • 466