Thursday, 21 September 2017

Pointer to obejct with dynamic memory allocation in C++

/*
 Pointer to object with dynamic memory allocation
*/
#include "iostream"
using namespace std;

class Box{
 public: 
  Box(){
   cout<<"\nConstructor called..";
  }
  ~Box(){
   cout<<"\nDestructor called.."<<endl;
  }
};

int main(){
 Box *b = new Box[2]; //constructor called twice 
// for(int i=0; i<2; i++)
 delete []b; // destructor called twice
 return 0;
}
/*
 OUTPUT
[pavan@localhost Home]$ g++ PointerToObject.cpp
[pavan@localhost Home]$ ./a.out 

Constructor called..
Constructor called..
Destructor called..

Destructor called..
[pavan@localhost Home]$ 

*/

No comments: