Using the C++ class constructor and the overridden values 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: Using the class constructor and the overridden values in C++ programming

To show: How to use the default and overridden constructor values of the C++ class object in C++ programming

 

// the C++ class constructor and destructor

#include <iostream>

using namespace std;

 

// class declaration

class TestConsDest

{

// member variable

public:

int TestVar;

// member functions/methods, constructor, destructor and other methods

public:

// constructor

TestConsDest();

// method

int DisplayValue();

// destructor

~TestConsDest();

};

 

// class implementation

// constructor

TestConsDest::TestConsDest()

{

// test how the constructor was invoked, static-retain the previous value

static int x=1;

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

x++;

}

 

// simple function returning a value

int TestConsDest::DisplayValue()

{

cout<<"I'm in DisplayValue() lor!"<<endl;

return TestVar = 100;

}

 

// destructor, clean up your work

TestConsDest::~TestConsDest()

{

// test how destructor was invoked

static int y=1;

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

y++;

// explicitly, assign a value

TestVar = 0;

}

 

// the main

int main()

{

// instantiate two objects. constructor should be invoked with proper memory allocation

TestConsDest Obj1, Obj2;

 

cout<<"\nI'm in main()...alalalalala....\n"<<endl;

cout<<"\nRe-confirm the allocation for Obj2 = "<<&Obj2<<endl;

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

cout<<"In main(), testing..."<<endl;

cout<<"What about Obj1 allocation? = "<<&Obj1<<endl;

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

 

return 0;

}

 

Output example:

 

In Constructor, pass #1

In Constructor, pass #2

I'm in main()...alalalalala....

 

Re-confirm the allocation for Obj2 = 0012FF48

I'm in DisplayValue() lor!

Default constructor value assigned = 100

In main(), testing...

What about Obj1 allocation? = 0012FF54

I'm in DisplayValue() lor!

Default constructor value assigned = 100

In Destructor, pass #1

In Destructor, pass #2

Press any key to continue . . .

 

 

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