Home | API | MFC | C++ | C | Previous | Next

Programming With C++

Structures

The C++ structures are similar to classes in C++ with the exception that all members are public by default. A structure is defined in C++ using keyword structure followed by the name of the class with the body of the 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 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;
}

The Basics | Variables and Constants | Arrays | C-strings | Expressions and Operators | Controlling Program Flow | C++ Functions | Pointers and References | Memory Map and Free Store | Smart Pointers | Classes | Structures | Inheritance | Polymorphism | Templates | The Standard Template Library | The STL String Class | Namespace | Type Conversions | Input and Output Streams | The C++ Preprocessor | Exception Handling

Last Updated: 15 September 2022