Lesson 1

Structure, union, enum

Is there object oriented world only?

Task 0

Create a program, which will create a point_3d structure. Next, create a variable of the structure.
Example: how to create a structure?

struct student
    int index;
    int semester;
Example: how to instantiate a structure?

int main()
    student s1, s2, s3;
    s1.index = 1;
    s1.semester = 3;

    s1.index = 2;
    s1.semester = 5;

    s1.index = 3;
    s1.semester = 7;

Task 1

Create a new structure (for example: car, university). Add some fields (numeric ones) and own enum. Can we create a value in enum called X, if X has been definied as a structure.
Example: how to create an enum?

enum person_type
Example: enum as a variable

int main()
    person_type somebody = guest;
        case student:
        case lecturer:
        case professor:
            std::cout << "Member of an university" << std::endl;
        case guest:
            std::cout << "Anybody" << std::endl;

Task 2

Create student’s structure:

  1. Add #include <string>
  2. Create a structure of a student with field name (string)
  3. Create two method headers before main function:

    • student create();
    • string to_string(student);
  4. Modify main function:

    • Create a new student via create method and assign value to a variable
    • Display information about student using to_string.
  5. Create definitions for:

    • create – it reads all information from standard input (terminal)
    • to_string – it returns a string build on all structure fields
Example: reading a string from standard input

int main()
    std::string text;
    std::getline(std::cin, text);

Task 3

Compare structure based programming and object oriented.

What is familiar? What is not?

Task 4

Create an union definition.

Then create a variable of created type.

Example: how to work with union?

union X
    int   integer;
    float floating;

int main()
    X x;
    x.integer = 3;
    x.floating = 3.14f;
    std::cout << x.integer << std::endl;
    std::cout << x.floating << std::endl;

Task 5

Create a namespace with 3 structures.

One of the structures should contain one member of another structure.

Create some methods headers inside a namespace.

You should use own enums as well.

Create implementations for yours methods.

Create an usage case for your code in main method.