Structs
Another feature of C++ similar to classes is the use of a struct.
Here is the definition of a struct:
Where in the above, the name is a useful name for the struct and the data variables are more than one variable with different data types. The struct is made for this just like a class. Notice that the semicolon after then closing brace is required.
Here is a nice example showing how to use a struct.
Example 1:
Struct program
Download source code here (Right click - Save Tagret As...)
The above program will output the contents of the person's struct. Notice that each of the
variables are of different data types (int, string and char).
Typedef
In C++, the typedef keyword is used to allow another name for a data type. Here is how it is declared.
where in the above, existing_type is a primitive type such as int, float, char etcÂ… and new_Name is your useful name for it. Let's see an example:
This program simply shows how to use the typedef. Notice that the program could have been
rewritten to the commented lines above.
Notice also that a typedef just creates another name for an already defined type, it does not
redefine it. The principal around a typedef is to allow outside programmers to read and
understand code better. This is a myth I might add.
The arrow -> operator
When dealing with pointers to a struct or a class, you can use the arrow operator -> to both dereference the pointer and assign a value at the same time. The variables must be declared public in a class for it to work.
Here is an example with a struct:
Example 2:
Sample arrow program
Download source code here (Right click - Save Tagret As...)
The output will be 9 4 when complete. Now here is an example with a class:
Notice again that the data variables are public.