6. Going Further with Types

About this Tutorial –

Objectives –

This course is aimed at students who need to get up to speed in C++. The course introduces object-oriented concepts and shows how they are implemented in C++. The course does not require awareness or familiarity with object-oriented programming techniques, but programming experience would be useful but not necessarily required.

Audience

Students who are new to object orientation (or programming) and need to learn C++.

Prerequisites

No previous experience in C++ programming is required. But any experience you do have in programming will help. Also no experience in Visual Studio is required. But again any experience you do have with programming development environments will be a valuable.

Contents

The C++ course covers these topics and more:

  • Introduction to C++: Key features of C++; Defining variables; Formulating expressions and statements; Built-in data types; Console input/output
  • Operators and types: Assignment; Compound Assignment; Increment and decrement operators; Const declarations; Type conversions
  • Going Further with Data Types: Enumerations; Arrays; Using the standard vector class; Using the standard string class; Structures

Download Solutions

Java tutorial


Overview

Estimated Time – 0.5 Hours

Not what you are looking? Try the next tutorial – Defining and Using Classes

Lab 1: Strings

Lab 1: Strings
  1. C-Style Strings
    • Before C++ came along, the C concept of a “string” was a character array
      • With a null terminator character ‘\0’ at the end
    • Example of declaring C-style strings
      • You can define the characters individually
        char name[] = { 'T', 'h', 'o', 'm', 'a', 's', '\0' };
      • Or you can use string-literal syntax (implicit null terminator)
        char name[] = "Emily";
    • There are standard functions for handling C-style strings
      • Either #include <cstring> and use the std namespace
      • Or #include <string.h>
  2. The C++ string Class
    • As we know, the C++ library has a string class
      • Lots of built-in functionality
      • Much better than using C-style strings
      • Only use C-style strings when interfacing with legacy C systems
    • To use the C++ string class
      • #include <string> and use the std namespace
  3. Using the C++ string class
    • Here are some examples that illustrate some capabilities of the C++ string class
      // Assignment or initialization.
      string s1 = "hello";
      string s2 = " world;
      string message = s1;
      // Concatenation.
      message += s2;
      message += ", have a nice day";
      // Comparison.
      if (message == "hello world, have a nice day")
      {
       // Indexing.
       message[0] = 'H';
      }
    • For full information:
      • See https://www.cplusplus.com/reference/string/string/
Lab
  1. Defining a struct and using it
    • In Visual Studio, create a new C++ project named GoingFurtherWithTypesApp in the student folder. Create a header file named Footballer.h. In this header file, define a structure template named Footballer, to hold:
      • The name of the footballer
      • His/her squad number
      • His/her position (e.g. GOALKEEPER, DEFENDER, MIDFIELDER, STRIKER
      • His/her goals scored (use a typedef for this type, e.g. to represent unsigned short)
        enum Position
        {
         GOALKEEPER, DEFENDER, MIDFIELDER, STRIKER
        };
        typedef unsigned short goals_t;
        struct Footballer
        {
         string name;
         int squadNumber;
         Position positionCode;
         goals_t goalsScored;
        };
      • View code file.
    • In main(), create a few footballer “objects” (ask the user to enter details). Output the details too
       Footballer footballer1;
       cout << "Enter a footballer's name: ";  getline(cin, footballer1.name);  cout << "Squad number: ";  cin >> footballer1.squadNumber;
       cout << "Position code (0=GOALKEEPER, 1=DEFENDER, 2=MIDFIELDER, 3=STRIKER): ";  int positionCode;  cin >> positionCode;
       footballer1.positionCode = (Position)positionCode;
       cout << "Goals scored: ";  cin >> footballer1.goalsScored;
       // Get rid of the CR character in the input buffer.
       cin.ignore();
       cout << footballer1.name    << " (squad number " << footballer1.squadNumber << ")"    << ", position code: " << footballer1.positionCode    << ", goals scored: " << footballer1.goalsScored << endl;
    • View code file.

Lab 2: Structures

Lab 2: Structures
  1. Overview
    • C++ allows you to group related information into a structure
      • Many related fields
      • Each field has a name and a data type
    • Why is this useful?
      • You can pass a structure into a function as a single item
      • You can copy one structure to another
    • Note:
      • Structures in C can only contain data
      • Structures in C++ can hold data + functions (similar to classes)
      • We'll just look at data-only structures in this chapter
  2. Defining a Structure Template
    • The first step is to define a structure template
      • Typically located in a header file
      • Specifies the name of the structure type, and defines all its fields
    • Example:
      struct Employee
      {
       int id;
       string name;
       double salary;
      };
  3. Creating Structure Objects
    • You can create a structure object like any other object
      • Note, these statements actually allocate storage for the structure objects (on the stack)
        Employee emp1, emp2, emp3;
        Employee team[3];
    • You can also initialize a structure when you create it:
      Employee emp1 = { 1, "Fran Smith", 100000 };
      Employee emp2 = { 2, "Ruth Elsom", 200000 };
      Employee emp3 = { 3, "Sara Evans", 300000 };
      Employee team[] =
      {
       { 4, "Clair Jones", 400000 },
       { 5, "Laura Brent", 500000 },
       { 6, "Heidi Wills", 600000 }
      };
  4. Using Structure Objects
    • To access fields in a structure object, use the . operator
    • If you have a pointer to a structure, use the -> operator
      • ptr->field is equivalent to (*ptr).field
        Employee emp;
        Employee * pEmp = &emp;
        pEmp->name = "Fred";
    • If you have a reference to a structure, use the . operator
      • Remember, references are just aliases for the underlying object
        Employee emp;
        Employee & rEmp = emp;
        rEmp.name = "Fred";
  5. Passing Structures to Functions
    • There are 3 ways to pass a structure to a function...
      • By value
        // Client
        Employee emp;
        DisplayEmployee1(emp);
        // Function
        void DisplayEmployee1(Employee e)
        {
         cout << e.id << e.name << e.salary; }
      • By pointer
        // Client
        Employee emp;
        DisplayEmployee2(&emp);
        // Function
        void DisplayEmployee2(const Employee * pe)
        {
         cout << pe->id << pe->name << pe->salary;
        }
      • By reference
        // Client
        Employee emp;
        DisplayEmployee3(emp);
        // Function
        void DisplayEmployee3(const Employee & e)
        {
         cout << e.id << e.name << e.salary; }
Lab
  1. Passing structures to/from functions
    • Write functions to do the following:
      • Display a footballer
        void DisplayFootballer(const Footballer *pFootballer)
        {
         cout << pFootballer->name
           << " (squad number " << pFootballer->squadNumber << ")"    << ", position code: " << pFootballer->positionCode
           << ", goals scored: " << pFootballer->goalsScored
           << (IsGood ? " is good." : " isn't good.") << endl; }
      • View code file.
      • Input a footballer
        void InputFootballer(Footballer *pFootballer)
        {
         cout << "Enter footballer's name: ";  getline(cin, pFootballer->name);
         cout << "Squad number: ";  cin >> pFootballer->squadNumber;
         cout << "Position code (0=GOALKEEPER, 1=DEFENDER, 2=MIDFIELDER, 3=STRIKER): ";  int positionCode;  cin >> positionCode;
         pFootballer->positionCode = (Position)positionCode;
         cout << "Goals scored: ";  cin >> pFootballer->goalsScored;
         cin.ignore();
        }
      • View code file.
      • Determine if a footballer is any good (goalsScored >= 10, bit harsh on the goalie...)
        bool IsGood(const Footballer *pFootballer)
        {
         return pFootballer->goalsScored >= 10;
        }
      • View code file.
    • Call these functions from main()
      Footballer anotherFootballer;
      InputFootballer(&anotherFootballer);
      DisplayFootballer(&anotherFootballer);
    • View code file.

Lab 3: Additional techniques

Lab 3: Additional techniques
  1. Typedefs
    • A typedef is another name for an existing type
      • Typically defined in a header file
        typedef existing_type pseudonym;
    • Typedef examples:
      typedef double money;
      typedef int pkey;
      typedef double length;
      typedef double speed;
    • Usage in client code:
      money mySalary, yourSalary;
      pkey employeeID, customerID;
      length screenWidth, screenHeight;
      speed lewisSpeed, sebastienSpeed;
    • Benefits:
      • Intent is clearer in client code
      • Centralized policy
      • Easier to maintain
  2. Enums
    • An enum is like a restricted-value integer
      • Typically defined in a header file
        enum enum_typename { pneumonic1, pneumonic2, pneumonic3, ... };
    • Examples:
      • By default, values start at 0 and increase in steps of 1
        enum Season { Spring, Summer, Autumn, Winter };
      • You can specify different values if you like
        enum Month { Jan=1, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec, Err=-1 };
    • Usage in client code:
      Season myFavouriteSeason = summer;
      Month myMonthOfBirth = Dec;
Lab
  1. Using arrays of structures
    • In main(), create an array of footballers. Call the array "team". There are 11 players in a real football team, but you can use a smaller number for testing :
      void InputTeam(Footballer team[], int numPlayers)
      {
       cout << endl << "Enter details for " << numPlayers << " players: " << endl;  for (int i = 0; i < numPlayers; i++)  {   InputFootballer(&team[i]);  } } void DisplayTeam(const Footballer team[], int numPlayers) {  cout << endl << "Here are the details for " << numPlayers << " players: " << endl;  for (int i = 0; i < numPlayers; i++)  {   DisplayFootballer(&team[i]);  } }
    • View code file.
    • Using the functions you've already written, initialize and display the footballer details
      Footballer team[5]; // 5-a-side.
      InputTeam(team, 5);
      DisplayTeam(team, 5);
    • View code file.

 

Well done. You have completed the tutorial in the C++ course. The next tutorial is

7. Defining and Using Classes


Back to beginning
Copyright © 2016 TalkIT®





If you liked this post, please comment with your suggestions to help others.
If you would like to see more content like this in the future, please fill-in our quick survey.
Scroll to Top