In this example for the C++ Documentation Tutorial, why are the pointers declared twice? -
i'm working through c++ documentation tutorial, , i'm having trouble understanding example of using pointers in constructor:
// example on constructors , destructors #include <iostream> using namespace std; class crectangle { int *width, *height; public: crectangle (int,int); ~crectangle (); int area () {return (*width * *height);} }; crectangle::crectangle (int a, int b) { width = new int; height = new int; *width = a; *height = b; } crectangle::~crectangle () { delete width; delete height; } int main () { crectangle rect (3,4), rectb (5,6); cout << "rect area: " << rect.area() << endl; cout << "rectb area: " << rectb.area() << endl; return 0; } it seems pointer *width declared twice. declared @ beginning of class: int *width, *height;, , declared when constructor initialized width = new int;.
why necessary declare pointer twice?
1) width = new int;
not declaration. allocating memory , assigning width. 2) int *with -> declaration.
hope helps.
Comments
Post a Comment