Solving the struct type problem using class, C++ code sample


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: Solving the struct aggregate data type problem using class in C++ programming

To show: How to use C++ class instead of struct in C++ programming to solve several issues




// using C++ class instead of struct

#include <iostream>

using namespace std;


// a simple class declaration

class rectangle


// private by default

int height;

int width;

// public, with two methods, which is the interface


int area(void);

void initialize(int, int);



// class implementation

int rectangle::area(void)


return (height * width);



void rectangle::initialize(int initial_height, int initial_width)


height = initial_height;

width = initial_width;



// normal structure - compare to a class

struct pole


int length; //public

int depth; //public



// the main()

void main(void)


// class object instantiation

rectangle wall, square;

// normal struct

pole lamp_pole;


// the following 3 lines invalid now, private member can be access only through methods


// wall.height = 12;

// wall.width = 10;

// square.height = square.width = 8;


// access member data through method coz of private by default




// as a comparison, normal struct member data access of course they are public

lamp_pole.length = 50;

lamp_pole.depth = 6;


// no interference, we can control the access as needed

cout<<"Using class instead of struct. Access through area() method"<<endl;


cout<<"Area of the wall, wall.area() = "<<wall.area()<<endl;

cout<<"Area of the square, square.area() = "<<square.area()<<endl<<endl;

cout<<endl<<"Access struct member as usual"<<endl;


cout<<"The length of the pole, (lamp_pole.length*lamp_pole.depth), is = "<<lamp_pole.length * lamp_pole.depth<<endl;

cout<<endl<<"Well, we can control the member data access as needed"<<endl;





Output example:


Using class instead of struct. Access through area() method


Area of the wall, wall.area() = 120

Area of the square, square.area() = 64


Access struct member as usual


The length of the pole, (lamp_pole.length*lamp_pole.depth), is = 300

Well, we can control the member data access as needed

Press any key to continue . . .



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