Cpp - Pointer Object pointer

Introduction

You can create a pointer to any object.

Bug *pBug = new Bug; 

This calls the default constructor-the constructor that takes no parameters.

Deleting Objects

When you call delete on a pointer to an object, the object's destructor is called before the memory is released.

Demo

#include <iostream> 
 
class Employee /*from   w  ww .  j ava 2s . co  m*/
{ 
public: 
    Employee(); 
    ~Employee(); 
private: 
    int itsAge; 
}; 
 
Employee::Employee() 
{ 
    std::cout << "Constructor called\n"; 
    itsAge = 1; 
} 
 
Employee::~Employee() 
{ 
    std::cout << "Destructor called\n"; 
} 
 
int main() 
{ 
    std::cout << "Employee emp ...\n"; 
    Employee emp; 
 
    std::cout << "Employee *ePointer = new Employee ...\n"; 
    Employee * ePointer = new Employee; 
 
    std::cout << "delete ePointer ...\n"; 
    delete ePointer; 
 
    std::cout << "Exiting.\n"; 
    return 0; 
}

Result

Related Topics