01.C++ OVERVIEW: CLASSES & DATA ABSTRACTION

SYNTAX

class classIdentifier
{
  private | protected:
    dataType selfVariableA, selfVariableB, ...;
  public:
    constructor();
    constructor(dataType variableA, dataType variableB);
  classMemberList
};

EXAMPLE

clockType                                   // this is the class name
{
  private:
    selfHours: int                          // private variable
    selfMinutes: int                        // private variable
    selfSeconds: int                        // private variable
  public:
    //constructors
    clockType()                             // constructor w/o parameters - initializes the variables of the class
    
    
    //function headers/prototypes
    //setter functions uses pass by value
    void setTime(int hour, int minute, int second);  // mutator function (aka setter in Python)
    //getter functions uses pass by reference
    const void getTime(int& hour, int& minute, int& second);            // accessor function (aka getter in Python)
    
    const void printTime();                 // keyword "const" doesn't change the value
    int incrementSeconds();
    int incrementMinutes();
    int incrementHours();
    const bool equalTime(const clockType&); // used to compare two class objects
};

DEFINITIONS

CLASS

  • a reserved keyword used to define a collection of fixed number of components

  • a class defines a data type

  • class members are the components of a class

  • classes are used for complex behavior or encapsulation and private members are accessed through getter/setter functions.

CLASS MEMBERS

  • variables

    • variables inside a class can't be initialized during declaration

  • functions

    • functions are declared as prototype only (heading only) and doesn't have definitions

    • can directly access any data or function member of the class

  • constructors/destructors

CLASS MEMBER: ACCESS SPECIFIER

  • private

    • by default, all members of a class are private even when not specified

    • if a member of a class is private, it can't be accessed outside of the class

    • c++ doesn't have fixed order; however, private members are typically declared first followed by the public members

  • public

    • use the label public w/ a colon "public" to make class members publicly accessible

  • protected

CLASS VARIABLE

  • an instantiated (created) class object

  • aka class object or class instance

  • declaration is similar to declaring any other variables

className variableName;
array declaration
className variable[elementNumber];

ACCESS OPERATOR

  • once an object is declared, it can access the public members of the class using the access operator (.)

className.classFunction();

OPERATIONS

  • most of C++'s built-in operations don't apply to classes

    • arithmetic operators can't be used on class objects unless the operators are overloaded/redefined (1st code block)

1st code block
className++;                      //this will produce a syntax error
  • relational operators used to compare two class objects for equality aren't allowed (2nd code block)

2nd code block
if (classNameA == classNameB)    //this will produce a syntax error
  • the two built-in operations that are valid for class objects are member access (.) and assignments (=) (3rd code block)

3rd code block
// this method won't produce errors
bool className::operator==(const classType& paramVar){
  return varA == paramVar.variableA && varB == paramVar.varB && varC == paramVar.varC;
}

REFERENCE VARIABLES & PARAMETERS

  • pass by reference

    • an efficient way to pass a variable as parameter

    • the actual parameter changes when the formal parameter changes as well (1st code block)

1st code block
//getter functions uses pass by reference
                             //-------> formal parameter <-------//
const void clockType::getTime(int& hour, int& minute, int& second){
  selfHours = hour;
  selfMinutes = minute;
  selfSeconds = second;
}
  • the "const" keyword in the formal parameter can be used to prevent the function from changing its value (2nd code block)

2nd code block
const bool clockType::equalTime(const clockType& time){
  return hr == time.hr && min == time.min && sec == time.sec;
}

SPECIAL CLASS FUNCTIONS

  • accessor functions

    • think of this as getters from Python

    • these are member functions that only accesses (doesn't modify) the value(s) of the data member(s)

//getter functions uses pass by reference
                             //-------> formal parameter <-------//
const void clockType::getTime(int& hour, int& minute, int& second){
  selfHours = hour;
  selfMinutes = minute;
  selfSeconds = second;
}
  • mutator functions

    • think of this as setters from Python

    • these are member functions that modifies the value(s) of the data member(s)

//setter functions uses pass by value
void clockType::setTime(int hour, int minute, int second){
  hour = selfHours;
  minute = selfMinutes;
  second = selfSeconds;
}
  • constant functions

    • these are member functions that can't modify data members

    • the keyword "const" makes the function unchangeable

const void clockType::printTime(){
  if (hours < 10)
    cout << 0;           // append leading 0
  cout << hours << ":";

  if (minutes < 10)
    cout << 0;           // append leading 0
  cout << minutes << ":";

  if (seconds < 10)
    cout << 0;           // append leading 0
  cout << seconds << "\n";
}
  • constructors

    • these are class members used to guarantee that data members are initialized

      • classes might have many constructors all having the same name as their classes

        • if a class has more than one constructor - they must have different sets of parameters

          • either in the number of parameters or types

    • constructors have no return type; so it's void

    • think of the C++ constructor as similar to Python constructor

C++ constructor
class clockType
{
  private:
    int selfHours, selfMinutes, selfSeconds;
  public:
    clockType();               //constructor - aka default constructor since it doesn't have parameters
};
Python constructor
class ServerMode:
  """Server Mode"""
  
  def __init__(self,host_ip:str=="0.0.0",host_port:int=1337):
  """Initialization"""
  self.hostIP = host_ip
  self.hostPort = host_port
  self.serverSocket = None

CONSTRUCTOR TYPES

  • with parameters

clockType::clockType(int hour, int minute, int second){
  selfHours = hour;
  selfMinutes = minute;
  selfSeconds = second;
}
  • without paramters

clockType::clockType(){
  selfHours = 0;                  //0 or NULL can be used to initialized the variables
  selfMinutes = 0;
  selfSeconds = 0;
}
  • invoking constructors

//invoking default constructor
className classObjectName;                                //method 1

int main()
{
  clockType t1;
  clockType t2(7,59,18);
  t1.printTime();
  t2.printTime();
}

//invoking parameterized constructor
className classObjectName(argument1, argument2,...);     //method 2

CONSTRUCTOR RULES

  • a constructor is automatically executed when a class variable is declared

  • if a class has no constructor(s), then C++ automatically provides the default constructor; however, the object declared will be uninitialized

  • if a class includes constructor(s) with parameter(s) & doesn't include default constructor, then C++ doesn't provide default constructor

  • if a class has constructors & you declare an array of class objects, then the class should have the default constructor

DESTRUCTORS

  • these are member functions which is used to destroy the objects created by constructors

  • destructors are automatically executed when the class object goes out of scope

  • destructors have the same name as the class name but preceded by ~ tilde operator

    • clockType:~clockType();

  • destructors doesn't take any argument or return value

  • a class can only have one destructor

clockType::clockType(){
  cout << "\nDestructor called";
}

ABSTRACT DATA TYPES

  • a type (or class) for objects whose behavior is defined by a set of values & a set of operations

  • the definition of ADT only mentions what operations are to be performed, but not how these operations will be implemented

INFORMATION HIDING

  • this simply means hiding the operations on the data

  • interface (header) file

    • contains the specification details

  • implementation file

    • contains the implementation details

STATIC MEMBERS

  • when a member of a class is declared as static, it means no matter how many objects of the class are created, there is only one copy of the static member

  • used the "static" keyword

  • a static member is shared by all objects of the class

  • if no other initialization is present (outside the class), all static data is initialized to zero when the first object is created

  • static member function can only access static data member, other static member functions and any other functions from outside the class

static.h file
class BankAccount
{
  int selfAccountNumber;
  double selfBalance;
  static int selfNumberOfAccounts;
  
  public:
    BankAccount(int accountNumber, double balance);
    void printStatus();
    void deposit(double amount);
    void withdraw(double amount);
    static int getNumberOfAccounts();
};

int BankAccount::numberOfAccounts = 0;
implementation.cpp
#include <iostream>
#include "static.h"

using namespace std;

int main()
{
  BankAccount b1(1000, 250.6);
  BankAccount b2(1001, 1345.9);
  
  b1.deposit(316.2);
  b2.withdraw(45.0);
  
  b1.printStatus();
  b2.printStatus();
  
  cout << "Number of accounts = " << BankAccount::getNumberOfAccounts();
  return 0;
}

CLASS IMPLEMENTATION: CLOCK

output of a C++ program that uses classes

UML

  • The negative sign (-) signifies that the member variables are private

  • The positive sign (+) signifies that the member functions are public

SOURCE CODE

VS > Create New Project > Console App or Empty Console Project
 Project Name:
 Location: DSU Project Directory
 Solution Name:
  * place solution & project in the same directory
  
VS > Solution Exporer
 Source Files > Add New Item
  * only one "main()" function is allowed
     - remove extra .cpp files when necessary

HEADER FILE: clock.h

/*################################################
# Name: Stephen Razon
# Student ID: 
# Date: 170741SEP24
# Filename: clock.h
# Dependency: N/A
################################################*/

class clockType
{
  private:
    int selfHours, selfMinutes, selfSeconds;
  public:
    //constructors
    clockType();
    clockType(int hour, int minute, int second);
    
    //Functions
    //mutator function (aka setter in Python)
    void setTime(int hour, int minute, int second);
    
    //accessor function (aka getter in Python)
    const void getTime(int& hour, int& minute, int& second);
    
    const void printTime();
    void incrementHours();
    void incrementMinutes();
    void incrementSeconds();
    
    //compares two class objects - overriding/redefinition
    const bool equalTime(const clockType&);
    bool operator==(const clockType&);
};

HEADER FILE: implementation.h

/*#######################################
# Name: Stephen Razon
# Student ID: 
# Date: 170741SEP24
# Filename: clockImplementation.h
# Dependency: clock.h
#######################################*/

#include "clock.h"       //this links the clock.h to implementation.h

using namespace std;
   
clockType::clockType(){
  selfHours = 0;
  selfMinutes = 0;
  selfSeconds = 0;
}

clockType::clockType(int hour, int minute, int second){
  selfHours = hour;
  selfMinutes = minute;
  selfSeconds = second;
}

void clockType::setTime(int hour, int minute, int second){
  selfHours = hour;
  selfMinutes = minute;
  selfSeconds = second;
}

const void clockType::getTime(int& hour, int& minute, int& second){
  hour = selfHours;
  minute = selfMinutes;
  second = selfSeconds;
}

const void clockType::printTime(){
  if (selfHours < 10){
    cout << 0;                 //append leading 0
  }
  cout << selfHours << ":";
  
  if (selfMinutes < 10){
    cout << 0;                 //append leading 0
  }
  cout << selfMinutes << ":";
  
  if (selfSeconds < 10){
    cout << 0;                 //append leading 0
  }
  cout << selfSeconds << "\n";
}

void clockType::incrementHours(){
  if (selfHours < 24){
    selfHours++;
  }
  else{
    selfHours = 0;
  }
}

void clockType::incrementMinutes(){
  selfMinutes++;
  if (selfMinutes < 60){
    selfMinutes = 0;
    incrementHours();
  }
}

void clockType::incrementSeconds(){
  selfSeconds++;
  if (selfSeconds < 60){
    selfSeconds = 0;
    incrementMinutes();
  }
}

const bool clockType::equalTime(const clockType& time){
  return (selfHours == time.selfHours) && (selfMinutes == time.selfMinutes) && (selfSeconds == time.selfSeconds);
}

bool clockType::operator==(const clockType& time){
  return equalTime(time);
}

SOURCE FILE: implementation.cpp

/*###################################
# Name: Stephen Razon
# Student ID: 
# Date: 170741SEP24
# Filename: implementation.cpp
# Dependency: clockImplementation.h
###################################*/

#include <iostream>
#include "clockImplementation.h"

using namespace std;

int main()
{
  clockType time1;
  clockType time2(7, 59, 18);
  
  time1.printTime();
  time2.printTime();
  cout << "\n";
  
  time1.setTime(2, 8, 59);
  time1.printTime();
  cout << "\n";
  
  time1.incrementSeconds();
  time1.printTime();
  time2.printTime();
  cout << "\n";
  
  cout << time1.equalTime(time2) << "\n";
  cout << (time1 == time2) << "\n\n";
  
  clockType clock[3];                       //create an array of 3 clockType
  for (int i = 0; i < 3; i++){
    clock[i].printTime();
  }
  
  return 0;
};

Last updated