Here is a simple rectangle area calculating cpp code and I have some questions around it:
#include <iostream>
#include <conio.h>
using namespace std;
class CRectangle
{
int *width, *heigth;
public:
CRectangle(int, int);
~CRectangle();
int area() { return (*width * *heigth);}
};
CRectangle :: CRectangle(int a, int b)
{
width = new int;
heigth = new int;
*width = a;
*heigth = b;
}
CRectangle :: ~CRectangle()
{
delete width;
delete heigth;
}
void main()
{
CRectangle rect1(3,4), rect2(5,6);
cout << "rect1 area = " << rect1.area() << "\n";
cout << "rect2 area = " << rect2.area();
getch();
}
- why in such object oriented codes we use pointers,I mean what's the advantage(s)?
- in this code after creating the object
rect1(3,4)
we createrect2(5,6)
,with doing this, logically (I think) 5 and 6 are replaced instead of 3 and 4 in the memory sections that width and height are pointing to , so 3 and 4 are not available anymore ,but they are.
Please explain what exactly happens?