A very simple C++ class program 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 data to demonstrate a very simple C++ class programming

To show: How to create and use a very simple C++ class in C++ programming

 

// a very simple C++ class

#include <iostream>

using namespace std;

 

// the base class declaration part

class BaseClass

{

// member variables declaration: declare all your variables here with optional access restriction modifiers: public, protected and private

public:

int p;

// protected access type provides access to the derived class only

protected:

float q;

// private is by default (implicitly), here we explicitly put the keyword

private:

char r;

// member functions or methods: define your functions here also with optional access restrictions

public:

// constructor

BaseClass();

// destructor

~BaseClass();

int Funct0();

private:

int Funct1();

protected:

void Funct2();

};

 

// class implementation part: define your functions or method here

// constructor

BaseClass::BaseClass()

{

cout<<"I'm in constructor, object construction initializations such as initial or default value..."<<endl;

}

 

int BaseClass::Funct0()

{

p = 200;

return p;

}

 

int BaseClass::Funct1()

{

cout<<"I'm in Funct1() method, doing something..."<<endl;

return 0;

}

 

void BaseClass::Funct2()

{

cout<<"I'm in Funct2() method, doing something..."<<endl;

}

 

// destructor implementation

BaseClass::~BaseClass()

{

cout<<"I'm in destructor, reset, destruct all the created object and return all the resources to the system..."<<endl;

}

 

// the main program: start instantiate objects here

int main(void)

{

// instantiate two objects of BaseClass type

BaseClass test1, test2;

 

cout<<endl<<"This just a class skeleton..."<<endl;

cout<<"It just simple, think simple!"<<endl<<endl;

cout<<"Accessing the public object's members: "<<test1.Funct0()<<endl<<endl;

 

return 0;

}

 

Output example:

 

I'm in constructor, object construction initializations such as initial or default value...

I'm in constructor, object construction initializations such as initial or default value...

 

This just a class skeleton...

It just simple, think simple!

 

Accessing the public object's members: 200

 

I'm in destructor, reset, destruct all the created object and return all the resources to the system...

I'm in destructor, reset, destruct all the created object and return all the resources to the system...

Press any key to continue . . .

 

 

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