Your browser doesn't support JavaScript Structures - Windows Programming

Structures

The C++ structures are similar to classes in C++ except that all members are public by default. A structure is defined in C++ using keyword structure followed by the class name with the body structure defined inside the curly brackets and terminated by a semicolon. Unlike structures in C structures in C++ can be initialised directly.

This code below creates a structure similar to the one in the class demonstration. Since all variables default to public, they can be accessed outside the class definition. Two objects of class box are instantiated and each member variable is initialised with a value. The total volume of the box is calculated by multiplying the individual box variables.

#include <iostream>
using namespace std;
struct box //class definition named box
{
int length;//declare public variable length
int height;//declare public variable height
int width;//declare public variable width
} box1;//instantiate class after class declaration (optional)
int main()
 {
box1.height=5,box1.length=30,box1.width=20;//set values of box1 member variables
cout << "Dimensions of box1 are - " << box1.height*box1.length*box1.width;//output box size
box box2;// instantiate class box 2
box2.height=5,box2.length=30,box2.width=20;//set values of box2 member variables
cout << "\nDimensions of box2 are - " << box2.height*box2.length*box2.width;//output box size
return 0;
}