Using struct aggregate data type that exhibits some problem for the instantiated objects in C and C++

 

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: Showing the problems using struct data type which the access to the member variables cannot be precisely control in C++ programming

To show: Using the struct that exhibits some problems for the objects creation where we cannot control the access to the member variables in C++ programming

 

// using struct that exhibits some problem for the object instantiations

#include <iostream>

using namespace std;

 

// function prototype

int area(int rectangle_height, int rectangle_width);

 

struct rectangle

{

// these are public

int height;

int width;

};

 

struct pole

{

// these are public

int length;

int depth;

};

 

// rectangle area

int surface_area(int rectangle_height, int rectangle_width)

{

return (rectangle_height * rectangle_width);

}

 

// main()

void main(void)

{

rectangle wall, square;

pole lamp_pole;

 

// assigning values

wall.height = 12;

wall.width = 10;

square.height = square.width = 8;

lamp_pole.length = 50;

lamp_pole.depth = 6;

 

cout<<"Area of wall = height x width"<<" = "<<surface_area(wall.height, wall.width)<<" OK!"<<endl;

cout<<"Area of square = height x width"<<" = "<<surface_area(square.height,square.width)<<" OK!"<<endl;

cout<<endl<<"But weird result here!!!"<<endl<<"Area of square = height of square x width of the wall?"<<endl;

cout<<" So it is non related surface area = "<<surface_area(square.height,wall.width)<<endl<<endl;

cout<<"Another wrong surface area = height of square x depth of lamp pole = "<<surface_area(square.height,lamp_pole.depth)<<endl;

cout<<endl<<"Because we can access the struct members publicly...."<<endl;

 

return;

}

 

Output example:

 

Area of wall = height x width = 120 OK!

Area of square = height x width = 64 OK!

But weird result here!!!

Area of square = height of square x width of the wall?

So it is non related surface area = 80

Another wrong surface area = height of square x depth of lamp pole = 48

Because we can access the struct members publicly....

Press any key to continue . . .

 

 

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