0% found this document useful (0 votes)
24 views23 pages

Introduction To Classes

The document discusses object-oriented programming and the C++ class Gradebook. It introduces classes as user-defined data types that encapsulate data and functions. A Gradebook class is defined with private data member courseName and public member functions to set, get, and display the course name. The summary creates two Gradebook objects, which implicitly calls the constructor and allows accessing member functions through the dot operator.

Uploaded by

U2103097 STUDENT
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views23 pages

Introduction To Classes

The document discusses object-oriented programming and the C++ class Gradebook. It introduces classes as user-defined data types that encapsulate data and functions. A Gradebook class is defined with private data member courseName and public member functions to set, get, and display the course name. The summary creates two Gradebook objects, which implicitly calls the constructor and allows accessing member functions through the dot operator.

Uploaded by

U2103097 STUDENT
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 23

KIG2007 : Computer Programming

Introduction to Classes

Semester 2, Session 2022/2023


Object-oriented programming
• The traditional procedural-oriented languages (such as C and Pascal)
focus on procedures, with function as the basic unit. You need to first
figure out all the functions and then think about how to represent data.
• The object-oriented languages focus on components that the user
perceives, with objects as the basic unit. You figure out all the objects
by putting all the data and operations that describe the user's interaction
with the data.
• Object-Oriented technology has many benefits:
• Ease in software design as you are dealing with high-level concepts
and abstractions.
• Ease in software maintenance: object-oriented software are easier to
understand, therefore easier to test, debug, and maintain.
• Reusable software: The fastest and safest way of developing a new
application is to reuse existing codes - fully tested and proven codes.
Procedural-oriented vs object-
oriented languages
C++ program structure
• Typical C++ programs consist of:
• a function main
• one or more classes – each containing data members and
member functions.
#include <iostream>
using namespace std;

class Gradebook {
public:
void displayMessage() {
class cout << "Welcome to the grade book” << endl;
}
};

int main(){
main Gradebook myGradeBook;
function myGradeBook.displayMessage();
}
Class
• A class can be visualized as a three-compartment box, as
illustrated:
• Classname (or identifier): identifies the class.
• Data Members or Variables (or attributes, states, fields): contains
the static attributes of the class.
• Member Functions (or methods, behaviors, operations): contains
the dynamic operations of the class.

class name Gradebook


(identifier)
data members nameOfCourse
(static attributes) grade
member functions getCourseName()
(dynamic attributes) printGrade()
Class definition
• starts with the keyword class followed by the class name; and
• the class body, enclosed by a pair of curly braces
• must be followed either by a semicolon or a list of declarations.

class class_name
{
access_specifier_1:
member1;
access_specifier_2:
member2;
...
};
Access-specifier
• access_specifier modifies the access rights for the members:
• public members are accessible from anywhere where the
object is visible.
• private members of a class are accessible only from within
other members of the same class.
• protected members are accessible from other members of the
same class but also from members of their derived classes.
• As a rule of thumb,
• data members should be declared private
• member functions should be declared public.
• By default, members would be assumed as private.
Class definition (Example)
class Circle { // class name
private:
double radius; // Data members (variables)
string color;
public:
double getRadius(); // Member functions
double getArea();
}

class Gradebook { // class name


private:
string courseName; // Data members (variables)
public:
void setCourseName(string name); // Member functions
string getCourseName();
void displayMessage();
}
Class member functions
• Member functions can be defined
• within the class definition; or
class Gradebook {
public:
void displayMessage() {
cout << "Welcome to the grade book!" << endl;
}
};

• separately using scope resolution operator (::).


class Gradebook {
public:
void displayMessage();
}; scope resolution operator

void Gradebook::displayMessage() {
cout << "Welcome to the grade book!" << endl;
}
Class object declaration
• A class variable is called a class object or class instance; or simply called
object. All the instances of a class have similar properties, as described in
the class definition.
• Typically, you cannot call a member function of a class until you create an
object of that class.

To create an object of a class, you have to:


1. declare an object identifier (name) of a particular class.
2. invoke a constructor to construct the object (i.e., allocate storage for
the instance and initialize the variables).

Syntax for class object declaration:


class_name classObject
Example:
// Construct 2 objects of the class Gradebook
Gradebook course1
Gradebook course2
Concept of class object
Class Car
Data members:
Colour
Brand
Model

Object name Ali’s car Mutu’s car Chong’s car


Colour Green Red Blue
Brand Ford Toyota Volkswagen
Model Mustang Prius Golf
Constructors
• C++ requires a constructor call for each object that’s created, which
helps ensure that each object is initialized properly before it’s used in
a program. The constructor call occurs implicitly when the object is
created.
• Two types of constructors:
• Default constructor
class_name classObject
e.g. Gradebook course1;
• Constructor with parameters
class_name classObject(argument1, argument2, …)
e.g. Gradebook course1(“KIE1004”);
• A constructor is a special member function that must be defined with
the same name as the class, so that the compiler can distinguish it
from the class’s other member functions.
• Constructors cannot return values, so they cannot specify a return
type (not even void).
Class object declaration (Example)
Suppose we created a class Gradebook
classname Gradebook
(identifier)
data members nameOfCourse
(static attributes) grade
member functions getCourseName()
(dynamic attributes) printGrade()

We can store the grades for two courses by creating two objects
“course1” and “course2”.

classname Gradebook course1 Gradebook course2

nameOfCourse = nameOfCourse =
data members “Course 1: KIE1004” “Course 2: KIE1005”
grade = {3.5, 3.7, …} grade = {3.9, 2.5, …}
getCourseName() getCourseName()
member functions printGrade() printGrade()
Accessing class members
• General syntax for an object to access a member of a class is:
classObject.memberName

• public members of objects of a class can be accessed using the


direct member access operator (.)
• private and protected members cannot be accessed directly
using direct member access operator (.)
Example – Gradebook project(1/3)
#include <iostream>

using namespace std;


Constructor has same name
// Gradebook class definition as class and no return type
class Gradebook {
public:
// constructor initializes courseName with string supplied as argument
Gradebook(string name) {
// call set function to initialize courseName
setCourseName(name);
}

// function to set the course name


void setCourseName(string name) { set function modifies private data
courseName = name; // store the course name in the object
}
Example – Gradebook project(2/3)
// function to get the course name
string getCourseName() { get function accesses private data
return courseName; // return object's courseName
}

// display a welcome message to the GradeBook user Use set and get functions,
void displayMessage() { even within the class
// call getCourseName to get the courseName
cout << "Welcome to the grade book for\n" << getCourseName()
<< "!" << endl;
}

private:
string courseName; // course name for this GradeBook
};
private members accessible only to
member functions of the class
End of class body
Example – Gradebook project(3/3)
// function main begins program execution
int main() {
// create two Gradebook objects
Gradebook course1("CS101 Introduction to C++ Programming");
Gradebook course2("CS102 Data Structures in C++");

// display initial value of courseName for each Gradebook


cout << “Gradebook1 created for course: " << course1.getCourseName()
<< "\nGradebook2 created for course: " << course2.getCourseName()
<< endl;
}
Use dot operator to call Use get function to
Creating objects implicitly Gradebook’s member function access private data
calls the constructor outside class definition
Unified Modeling Language (UML)
• UML is a standardized graphical language used by software
developers to represent their object-oriented systems.

UML class diagram of the class Gradebook:


Name of the class
Gradebook
- sign: – courseName: string Data members and
private member
their data types
+ setCourseName(string): void Member function
+ sign: + getCourseName(): string name, parameter list,
public member + displayMessage(): void return type of the
+ Gradebook() function

Constructor
# sign: protected member
Placing a class in a separate file
• .cpp file is known as a source-code file
• Header files (.h)
• Separate files in which class definitions are placed
• Allow compiler to recognize the classes when used elsewhere
• Generally have .h filename extensions
• can be included in any program to reuse the class
• Programs use #include pre-processing directives to include
header files
• Pre-processor first looks in current directory
• If the file is not found, looks in C++ Standard Library directory
• To ensure that the preprocessor can locate header files correctly,
#include preprocessor directives should place the names of user-
defined header files in quotes (e.g., "GradeBook.h") and place
the names of C++ Standard Library header files in angle brackets
(e.g., <iostream>).
Placing a class in a separate file
• For better software engineering, it is recommended that the class
declaration and implementation be kept in 2 separate files: declaration is a
header file ".h"; while implementation in a ".cpp".
#include <iostream> #include <iostream>
using namespace std; #include “GradeBook.h”
using namespace std;
class Gradebook {
public: int main(){
void displayMessage() { Gradebook myGradeBook;
cout << "Welcome to the grade myGradeBook.displayMessage();
book” << endl; }
}
};

GradeBook.h main.cpp

declaration is a header file ".h" implementation in a source file".cpp"


Placing a class in a separate file
(Example)
Separate the code from previous example (Gradebook project) into 2
separate files – GradeBook.h (contains Gradebook class definition)
and main.cpp (uses class Gradebook).

Also, define the member functions separately using scope resolution


operator (::).
Separating interface from implementation
• In our prior examples, each class definition contained the complete
definitions of the class’s public member functions and the
declarations of its private data members.
• However, it’s better software engineering to define member functions
outside the class definition, so that their implementation details can
be hidden from the client code.
• In the example of Gradebook project, we will have 3 files:
• GradeBook.h: Defining a class’s Interface with function
prototypes that describe the class’s public interface without
revealing the class’s member-function implementations
• GradeBook.cpp: Defining member functions in a separate
source-code file
 Use binary scope resolution operator (::) to “tie” each member function
to the class definition
• main.cpp: Contains the main function (client source code) which
implements the class.
Separating interface from implementation

Compilation and linking process


from the perspectives of the
Gradebook class programmer
and the client-code programmer

You might also like