7. Defining and Using Classes

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 – Additional Class Techniques

Lab 1: Essential concepts

Lab 1: Essential concepts
  1. What is a Class?
    • A class is a representation of a real-world entity
      • Defines data, plus methods to work on that data
      • Data is typically private, to enforce encapsulation
    • Domain classes
      • Specific to your business domain
      • E.g. BankAccount, Customer, Patient, MedicalRecord
    • Infrastructure classes
      • Implement technical infrastructure layer
      • E.g. NetworkConnection, AccountsDataAccess, IPAddress
    • Exception classes
      • Represent known types of error
      • E.g. Exception, BankException, CustomerException
    • Etc…
  2. What is an Object?
    • An object is an instance of a class
      • You can just create an object using Classname objname; syntax
      • You can also create/destroy dynamically using new/delete keywords (see later)
    • Object management
      • Unlike some OO languages (notably Java and C#), C++ doesn’t use garbage-collected
      • It’s the responsibility of the programmer to ensure objects are disposed of (we’ll come back to this point when we look at new/delete later in the course)
  3. OO Modelling
    • During OO analysis and design, you map the real world into candidate classes in your application
      • Use-case modelling
      • Class diagrams
      • Sequence diagrams
      • Object diagrams
      • State diagrams
    • UML is the standard OO notation
      • Widely used
      • Degree of ceremony varies from one organization to another
Lab
  1. Defining a class
    • Exercise 1: Defining a class
      In Visual Studio, create a new C++ project named DefiningUsingClassesApp in the student folder.
    • Add a new class named BankAccount. In BankAccount.h, declare the following private data members:
      • Name of the account holder (a string)
      • Current balance (a double)
      • Fees payable on the account (a double) – this allows the bank to make money
        private:
         // State.
         string accountHolder;
         double currentBalance;
         double feesPayable;
         int tranAmount;
         string tranList[TRAN_SIZE];
        };
      • View code file.
    • Still in BankAccount.h, declare the following public member functions:
      • A constructor (note, the only mandatory info is the account holder’s name)
      • Functions to allow the client to deposit and withdraw an amount in the account
      • Some display / getter functions as appropriate (note, these should be const member functions)
        public:
         // Public interface.
         BankAccount(const string & name);
         void Deposit(double amount);
         void Withdraw(double amount);
         string GetAccountHolder() const;
         double GetBalance() const;
         double GetFeesPayable() const;
         int GetTranAmount() const;
         void SetTranAmount(int amount);
         void PrintTransactions() const;
      • View code file.

Lab 2: Defining a class

Lab 2: Defining a class
  1. General Syntax for Class Declarations
    • General syntax for a class declaration (in a .h file)
      • Similar to a struct template, but with function prototypes added into the mix
        class ClassName
        {
         // Define members (data and method prototypes) here.
        };
    • Example:
      class BankAccount
      {
       // Define BankAccount data and BankAccount method prototypes here.
      };
  2. Access Specifiers
    • When you define members (i.e. data and methods) in a class, you can use the following access specifiers:
      • public:
        • Accessible by anyone
        • Methods and constants are often public
        • This is the default accessibility in a struct
      • private:
        • Accessible only by class itself
        • Data and helper methods are usually private
        • This is the default accessibility in a class
      • protected:
        • Accessible by class and by classes that inherit from it (see Inheritance later in the course)
        • Allow access to members that are hidden from general client code
  3. Defining Instance Variables
    • A class can define any number of instance variables
      • Each instance will have its own set of these variables
        class BankAccount
        {
        private:
         string accountHolder;
         int id;
         double balance;
         ...
        };
  4. Defining Getters and Setters
    • It’s sometimes useful to define public getters and/or setters for private instance variables
      • Allows external code/tools to get/set values as “properties”
        // Header File
        class BankAccount
        {
         ...
        public:
         string GetAccountHolder();
         void SetAccountHolder(string ah);
        };
        // CPP File
        #include "BankAccount.h"
        string BankAccount::GetAccountHolder()
        {
         return accountHolder;
        }
        void BankAccount::SetAccountHolder(string ah)
        {
         accountHolder = ah;
        }
  5. The this Keyword
    • The this keyword is a pointer to the current object”
      • Allows instance methods to explicitly access instance variables and instance methods on the “current” object
      • The following are semantically identical
        void BankAccount::SetAccountHolder(string ah)
        {
         accountHolder = ah;
        }
        void BankAccount::SetAccountHolder(string ah)
        {
         this->accountHolder = ah;
        }
    • Uses of this:
      • Allows use of the same name for local vars and instance vars
      • Allows you to pass a “pointer to self” into callback methods
      • Triggers IntelliSense
  6. Defining Instance Methods
    • A class can define any number of instance methods
      • So-called because each they operate on a particular instance
        // Header
        class BankAccount
        {
         ...
        public:
         double Deposit(double amount);
         double Withdraw(double amount);
        };
        // Cpp File
        #include "BankAccount.h"
        double BankAccount::Deposit(double amount)
        {
         balance += amount;
         return balance;
        }
        double BankAccount::Withdraw(double amount)
        {
         balance -= amount;
         return balance;
        }
  7. Overloading Methods
    • A class can contain several methods with the same name
      • As long as the number (or types) or parameters is different
      • This is known as “overloading methods”
        // Header
        class BankAccount
        {
         ...
        public:
         double Deposit(double amount);
         double Deposit(int dollars, int cents);
        };
        // Cpp File
        #include "BankAccount.h"
        double BankAccount::Deposit(double amount)
        {
         balance += amount;
         return balance;
        }
        double BankAccount::Deposit(int dollars, int cents)
        {
         double amount = dollars + cents/100;
         return this->Deposit(amount);
        }
  8. Scope
    • The concept of “scope” is important in C++
      • When you mention a variable name (or method name, etc), the compiler looks in the following scopes to find its definition
      • T7P1

    • You can force the compiler to look in a specific scope
      • To look in class scope:
        ClassName::identifier
      • To look in global scope:
        ::identifier
Lab
  1. Implementing class behaviour
    • In BankAccount.cpp, implement all the member functions for the BankAccount class
      BankAccount::BankAccount(const string & name)
      {
       accountHolder = name;
       currentBalance = 0;
       feesPayable = 0;
       tranAmount = 0;
      }
      string BankAccount::GetAccountHolder() const
      {
       return accountHolder;
      }
      double BankAccount::GetBalance() const
      {
       return currentBalance;
      }
      double BankAccount::GetFeesPayable() const
      {
       return feesPayable;
      }
      // Try and add a AddTransaction yourself, the solution is always available to download from the top of the tutorial
    • View code file.
    • Note that the deposit and withdraw methods should levy a fee against the bank account – the user has to pay a certain fee every time they deposit or withdraw. Harsh yes, but hey, this is the Dawning of the Age of Austerity
      void BankAccount::Deposit(double amount)
      {
       feesPayable += FEE_PAYABLE;
       currentBalance += amount;
       AddTransaction(amount, currentBalance, "[D]");
      }
      // Withdraw Function
      void BankAccount::Withdraw(double amount)
      {
       if (amount > currentBalance)
       {
        cout << "Insufficient funds!" << endl;  }  else  {   feesPayable += FEE_PAYABLE;   currentBalance -= amount;   AddTransaction(amount, currentBalance, "[W]");  } }
    • View code file.
    • Compile your application and fix any compiler errors

Lab 3: Creating and using objects

Lab 3: Creating and using objects
  1. Creating an Object
    • To create an instance (object) of the class:
      • You can just create it like a normal variable
      • Creates the object on the "stack", local to this function
      • Automatically popped off the stack (i.e. de-allocated) on exit from the function
        void someFunctionInMyCode()
        {
         // Create a BankAccount object, on the stack.
         // Note, unlike Java and C#, you don't have to use the new keyword.
         // (Although it is possible to use new, we'll come back to that later...)
         BankAccount myAccount;
         // Use object here...
        } // Object automatically disappears here.
  2. Invoking Methods on an Object
    • To invoke (public) methods on an object:
      • Use the object.method() syntax
      • Pass parameters if necessary
        myAccount.Deposit(100000);
        double b = myAccount.GetBalance();
Lab
  1. Creating and using objects
    • Add code to main(), to create BankAccount objects and fully test the functionality implemented by BankAccount
      BankAccount myacc("John Smith");
      myacc.Deposit(100);
      cout << "Balance: " << myacc.GetBalance() << endl; myacc.Withdraw(50); myacc.Deposit(100); myacc.Deposit(50); myacc.Deposit(30); myacc.Deposit(10); myacc.Withdraw(100); myacc.Withdraw(10); myacc.Withdraw(10); myacc.Withdraw(10); myacc.Withdraw(10); myacc.Withdraw(20); cout << "Balance: " << myacc.GetBalance() << endl; myacc.PrintTransactions(); return 0;
    • View code file.
    • Compile your application and then run it. Verify it behaves as expected

Lab 4: Initialization

Lab 4: Initialization
  1. The Role of Constructors
    • You can define constructors in your class to perform initialization
      • A constructor is a method with the same name as the class
      • Typically public, to allow client code to access
      • No return type, not even void
      • Can specify parameters
  2. Defining a Default Constructor
    • A constructor that has no parameters is called the "default constructor"
      • Called automatically when you create an object with no parameters
        // Header
        class BankAccount
        {
         ...
        public:
         BankAccount();
         ...
        };
        // Cpp file
        #include "BankAccount.h"
        BankAccount::BankAccount()
        {
         accountHolder = "Unknown";
         id = -1;
         balance = 0;
        }
  3. Defining Constructors with Parameters
    • You can also define constructor(s) that take parameters
      • Called when you create an object with parameters
        // Header File
        class BankAccount
        {
         ...
        public:
         BankAccount(string ah, int id, double initBal);
         ...
        };
        // Cpp File
        #include "BankAccount.h"
        BankAccount::BankAccount(string ah, int id, double initBal)
        {
         this->accountHolder = ah;
         this->id = id;
         this->balance = initBal;
        }
        // Client
        // Create an object
        BankAccount acc2("John Smith", 1, 1000);

 

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

8. Additional Class Techniques


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