Using the C++ new and delete keywords for class object code example

 

Compiler: Visual C++ Express Edition 2005

Compiled on Platform: Windows XP Pro SP2

Header file: Standard

Additional library: none/default

Additional project setting: Set project to be compiled as C++

Project -> your_project_name Properties -> Configuration Properties -> C/C++ -> Advanced -> Compiled As: Compiled as C++ Code (/TP)

Other info: none

To do: Tracing the program execution flow of the C++ class object constructor and destructor with new and delete keywords in C++ programming

To show: How to use the C++ new and delete keywords for class object and tracing the class constructor and destructor execution order in C++ programming

 

// using the C++ new and delete keywords in class object example with the class constructor and destructor execution order

#include <iostream>

using namespace std;

 

// class declaration part

class TestNewDel

{

// member variables...

private:

int TestVar;

char *TestPtr;

 

// member functions, constructor and destructor

public:

TestNewDel();

int DisplayValue();

char* DisplayStr();

~TestNewDel();

};

 

// class implementation

// constructor

TestNewDel::TestNewDel()

{

// test how the constructor is invoked

static int x=1;

cout<<"In Constructor, pass #"<<x<<endl;

x++;

}

 

// simple function returning a value

int TestNewDel::DisplayValue()

{

return TestVar = 200;

}

 

// another function returning a string

char* TestNewDel::DisplayStr()

{

TestPtr = "Testing the new and delete";

return TestPtr;

}

 

// destructor

TestNewDel::~TestNewDel()

{

// test how destructor is invoked, use static type to retain previous value

static int y=1;

cout<<"In Destructor, pass #"<<y<<endl;

y++;

// clean up explicitly

TestVar = 0;

}

 

// main program

int main(void)

{

// instantiate an object, constructor should be invoked with proper memory allocation

TestNewDel Obj1;

 

cout<<"In main, testing 1...2...3..."<<endl;

 

// display the data value

cout<<"Default constructor value assign to Obj1 = "<<Obj1.DisplayValue()<<endl;

 

// invoke constructor explicitly, remember to clean up later explicitly

TestNewDel* Obj2 = new TestNewDel;

 

// re-confirm the allocation for Obj2

if(!Obj2)

cout<<"Allocation to Obj2 failed!"<<endl;

else

cout<<"Allocation to Obj2 is OK!"<<endl;

 

// display the data value

cout<<"Default constructor value "

<<"\n assigned to Obj2 = "<<"\'"<<Obj2->DisplayStr()<<"\'"<<endl;

 

// clean up the allocation explicitly

delete Obj2;

 

return 0;

}

 

Output example:

 

In Constructor, pass #1

In main, testing 1...2...3...

Default constructor value assign to Obj1 = 200

In Constructor, pass #2

Allocation to Obj2 is OK!

Default constructor value

assigned to Obj2 = 'Testing the new and delete'

In Destructor, pass #1

In Destructor, pass #2

Press any key to continue . . .

 

 

C and C++ Programming Resources | C & C++ Code Example Index