The C++ class and object with constructor and destructor execution order 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: Displaying some strings while tracing the constructor and destructor execution order in C++ programming

To show: A very simple C++ class and object instantiation with constructor and destructor execution flow

 

// class and object

#include <iostream>

using namespace std;

 

class PlayText

{

// private by default

char *NewPointerVariable;

public:

// constructor

PlayText(char *InputFromMainProgPointer);

// destructor

~PlayText();

int GetData(void);

};

 

PlayText::PlayText(char *InputFromMainProgPointer)

{

cout<<"Location: constructor implementation part"<<endl;

cout<<"Examine the execution flow!!!"<<endl;

cout<<"String brought by object from main program is "<<"\""<<InputFromMainProgPointer<<"\""<<endl;

cout<<"through pointer variable *InputFromMainProgPointer"<<endl;

cout<<"Assign this string to class member pointer variable"<<endl;

cout<<"*NewPointerVariable"<<endl<<endl;

cout<<"Next Location: Main program"<<endl<<endl;

 

NewPointerVariable = InputFromMainProgPointer;

}

 

PlayText::~PlayText()

{

cout<<endl<<"Final location: Destructor lol!"<<endl<<endl;

}

 

int PlayText::GetData(void)

{

cout<<NewPointerVariable<<" = ";

return 100;

}

 

void main(void)

{

PlayText small("of small size");

cout<<"cout string of main program \"Area of...\" mix "<<endl;

cout<<"with NewPointerVariable variable and silly integer value"<<endl;

cout<<"from implementation part by using small.GetData()...."<<endl;

cout<<"Go to implementation part after next cout, and the output is: "<<endl;

cout<<"Area of wall surface ";

cout<<small.GetData()<<endl;

 

return;

}

 

Output example:

 

Location: constructor implementation part

Examine the execution flow!!!

String brought by object from main program is "of small size"

through pointer variable *InputFromMainProgPointer

Assign this string to class member pointer variable

*NewPointerVariable

 

Next Location: Main program

 

cout string of main program "Area of..." mix

with NewPointerVariable variable and silly integer value

from implementation part by using small.GetData()....

Go to implementation part after next cout, and the output is:

Area of wall surface of small size = 100

Final location: Destructor lol!

Press any key to continue . . .

 

 

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