C++ Guide

Download as pdf or txt
Download as pdf or txt
You are on page 1of 27

PROGRAMME: HND in computer Engineering

COURSE: Computer Programming (C/C++ Language)

CODE: CTE313

Unit: 2.0

Prerequisites:
In this Module, we are going to work you through from absolute Basics to Advance Concept
of programming Language Before you start practicing with various types of examples given in
C++ Language and building projects. So Average knowledge of programming language will
be helpful and a device that will ensure frequent practice.

1
“A computer is an electronic device capable of performing commands. The basic
commands that a computer performs are input (get data), output (display result),
storage, and performance of arithmetic and logical operations.”

What is Programming:
“A computer program is a series of instructions given to a computer to perform a specific task”.
It can be further explained as breaking apart more complex idea into a smallest instruction and
using a programming language to write those instructions. A computer will do exactly what
you tell them, so the instructions you give should better make sense.
In programming language, we write these instructions using syntax. Syntax are like sentences
in English Language they use words numbers and punctuations to express a single thought.
Most programming syntax are short just a few words. The words and punctuation you use
depends on the programming language. Some language requires your syntax to end with semi
colons while others don’t, some uses full uppercase for naming convention some lowercase
and others don’t care at all it all depends on your preference.

Programming Methodologies:
Two popular approaches to programming design are the structured approach and the object-
oriented approach, which are outlined below

Structured Programming Language:


Dividing a problem into smaller subproblems is called structured design. Each subproblem is
then analysed, and a solution is obtained to solve the subproblem. The solutions to all of the
subproblems are then combined to solve the overall problem. This process of implementing a
structured design is called structured programming. The structured-design approach is also
known as top-down design, bottom-up design, stepwise refinement, and modular programming

Object-Oriented Programming:
Object-oriented design (OOD) is a widely used programming methodology. In OOD, the first
step in the problem-solving process is to identify the components called objects, which form
the basis of the solution, and to determine how these objects interact with one another. For
example, suppose you want to write a program that automates the video rental process for a
local video store. The two main objects in this problem are the video and the customer. After
identifying the objects, the next step is to specify for each object the relevant data and possible
operations to be performed on that data. For example, for a video object, the data might include

• Movie name
• The actors
• Producer
• Production company
• Number of copies in stock etc.

2
Some of the operations on a video object might include:

• checking the name of the movie


• reducing the number of copies in stock by one after a copy is rented
• incrementing the number of copies in stock by one after a customer returns a
particular video
This illustrates that each object consists of data and operations on that data. An object combines
data and operations on the data into a single unit. In OOD, the final program is a collection of
interacting objects. A programming language that implements OOD is called an object-oriented
programming (OOP) language. You will learn about the many advantages of OOD in later
chapters.

Why do we have various programming Languages?


A lot of people might have a question in mind why can’t we have a single programming
Language that does everything if what we are doing is to write a simple instruction for the
computer to understand.
That language Exist is called the “Machine Code/Language”. These are the real instructions
that run directly on your computer hardware. We don’t learn it because it is meant for the
machine/CPU to understand not human beings. And because of machine code works at the
level of CPU it would be different machine code for different models of CPU. Writing a
machine language is theoretically possible but it will take you so long and tedious that doesn’t
even worth it.
So different programming languages are created to bridge the gap between us human beings
and the computer hardware. Some of these languages are actually quite close to machine code.
The closest is something known as “ASSEMBLY LANGUAGE” or low-Level Language.

Figure i.0

3
Writing source code:
To write a source code you need a text editor that comes with the operating system like Notepad
on windows or TextEdit on Mac. It works smoothly to write any programming language. All
you are required is to save with the appropriate file extension for each.

Figure ii

Why C++:
The most important thing while learning C++ is to focus on concepts.
The purpose of learning a programming language is to become a better programmer; that is, to
become more effective at designing and implementing new systems and at maintaining old
ones.
C++ supports a variety of programming styles. You can write in the style of Fortran, C,
Smalltalk, etc., in any language. Each style can achieve its aims effectively while maintaining
runtime and space efficiency C++ is being highly used to write device drivers and other
software that rely on direct manipulation of hardware under real-time constraints.

4
First Program

Above is a code snippet on basic simple program in C++ that will output a “Hello world”
Message on the console. If you are able to build and run this program successfully it means
you thoroughly follow the installation procedure given in class, else you might have a problem
with the compiler. Kindly read all error messages carefully apply the suggested solution or
even google it online you will definitely come across a reliable solution. Just be more patient
errors are part of the growth.

Lexical Elements:
Programming languages can be regarded in much the same way as linguistic languages such
as English French Spanish Portuguese etc. The lexical elements of a programming Language
consist of the syntax (words), punctuations and scope (semantics).

Syntax:
Syntax can be said as the rules for writing a language. For each language it has a specific syntax
to follow. Putting together the words and punctuations of a program in a legal and correct
manner.

Semantics:
Basically, semantics is a methodology in which you put together your syntax to be logically
correct. To learn the semantics of programming language it is to learn how to articulate an
algorithm using the language. Semantics of computer programming are generally harder to
learn than syntax but more easily transferred to other language.

Punctuations
These are the special characters such as { , : ; ‘’ () } and much more. They are used to satisfy
the rules of the syntax. Some programming language are not strict with certain punctuations
which means you can omit semi colon and the program will run smoothly.

Operators
Binary arithmetic operators include, ( +,-,/,*,% ), unary arithmetic operators are ( ++, -- ) and
the assignment operators (=, +=, -=, *= )

5
In a nut shell, we have multiple programming languages and does not mean we should learn
all. For each language has a purpose so the ball is in your court to make the choice. Luckily,
almost all the language has one thing in common, which is the semantics. If you learn a
particular language perfectly it will be a piece of cake switching to other languages because
you already have an idea on how the logic will be implemented so you just need to learn the
syntax of the new language.

Identifiers/Variable Name
Identifiers are names given to variables and functions. In identifying your variables, there are
key rules that must be followed if not the identifier will be invalid. The rules are as follows:

i. Can not begin with a Digit. Example (int 2age) ×


ii. It is case sensitive. Which means (name, Name and NAME) is completely different
variables holding different data.
iii. Keywords cannot be used. All programming languages have a reserved keyword,
such keywords cannot be used as part of naming convention.
iv. Finally, all identifiers should be meaningful so that the codes will be readable/
easier to review by an external analyst.

VARIABLES
Variable is a placeholder that stores in values of different data types. To declare a variable in C++, you
first specify what type of value you intend to store which will determine the data type. We have
numerous data type examples include

a. Integers (int)
b. Boolean (bool)
c. Float
d. String (str)
e. Character (char)

Each data type has a function. Integers store in positive and negative numbers without decimal
points, Floats hold integers with decimal points only, Boolean holds in truth (1) and false (0)
values, character stores a single character such as (*, #, $, %) and string stores in sequence of
characters as shown below

6
Basic Keywords in C++
These are words that are explicitly reserved and have strict meaning to the complier. It cannot
be redefined or redeclared. Example of C++ keywords include string, int, cout, if, for, while,
function class, return, struct, end etc.

Simple Statements and Compound statements


A statement is a command given to the computer that instruct the computer to take a specific
action such as collecting input from the user or display something to the console. An entire
computer program such as operating systems, Microsoft office etc. are made up of series of
statements. A simple statement is usually made up of a single line e.g
Cout<<” Engr. Saidu Gidado” <<endl;

A compound statements can be referred to as block of statements, it typically appears as the


body of other statements such as the if statements, for loops. It is made up of two or more
syntax that are executed together. Usually compound statements are surrounded within Curly
braces {…}.
Example of compound statement in C++ programming:

7
CONTROL STRUCTURES:
A computer can process a program in one of the following ways: in sequence; selectively, by
making a choice, which is also called a branch; repetitively, by executing a statement over and
over, using a structure called a loop; or by calling a function. The diagram below illustrates the
three types of program flow

Before you can learn about selection and repetition, you must understand the nature of
conditional statements and how to use them. Consider the following three statements:

1. if (score is greater than or equal to 90) grade is A


2. if (hours worked are less than or equal to 40) wages = rate * hours otherwise wages =
(rate * 40) + 1.5 *(rate *(hours – 40))
3. if (temperature is greater than 70 degrees and it is not raining) Go golfing

These statements are examples of conditional statements. You can see that certain statements
are to be executed only if certain conditions are met. A condition is met if it evaluates to true.
For example,
statement 1: score is greater than or equal to 90 is true if the value of score is greater than or
equal to 90; it is false otherwise. For example, if the value of score is 95, the statement evaluates
to true. Similarly, if the value of score is 86, the statement evaluates to false. It would be useful
if the computer could recognize these types of statements to be true for appropriate values.
Furthermore, in certain situations, the truth or falsity of a statement could depend on more than
one condition. For example, in statement 3, both temperature is greater than 70 degrees and it
is not raining must be true to recommend golfing.

8
RELATIONAL OPERATORS:
To write a condition for a compiler to understand you need to know relational operators
available in C++ programming language
In C++, a condition is represented by a logical (Boolean) expression. An expression that has a
value of either true or false is called a logical (Boolean) expression.
Consider the expression:
i > j;
If this expression is a logical expression, it will have the value true if the value of i is greater
than the value of j; otherwise, it will have the value false. The symbol > is called a relational
operator. A relational operator allows you to make comparisons in a program. C++ includes
six relational operators that allow you to state conditions and make comparisons. Table below
list the relational operators.
Operator Description
== Equals to
!= Not Equals to
< Less than
<= Less than or equal to
> Greater than
>= Greater than or equal to

Logical (Boolean) Operators and Logical Expressions


Logical (Boolean) operators enable you to combine logical expressions. C++ has three logical
(Boolean) operators, as shown in Table below:
Operator Description
! NOT
&& AND
|| OR

CONDITIONAL OPERATOR:
IF statements:
The most common type of decision structure is the if statements. This exist in all
programming languages but are implemented slightly different. The conditions are usually
written with relational and conditional operators.

9
The syntax of if statement as follows: IF (condition){
Code goes here…
}
Example:
Create a c++ program that determine the largest number between two integers collected from
the user.
Source code:

#include <iostream>
using namespace std;
int main()
{
int num1,num2;
cout<<"Enter the integer Values: "<<endl;
cin >>num1>>num2;
if(num1 > num2){
cout<<"The largest Number is:"<<num1;
}
else{
cout<<"The largest Number is:"<<num2;
}

return 0;
}

NB:
In a situation where by you have more than one condition then you create a new block called
the Else-if block. The syntax as follows:
If(condition 1){
//Codes…
}
Else if(condition 2){
//Codes…
}
Else{
//if all conditions are false this block of code will
//execute
}

you can create as much else-if block you wish but it’s not preferable rather if you have multiple
condition you use the SWITCH statements.

10
Case Study 1:
1. Computer Engineering Exams office need a grading system application that will
automatically grade the student’s performance base on the total score given. Assuming
the exams office requirements are as follows:

Scores from:
0-49: Repeat session(F)
50-69: pass with probation(C)
70-79: fairly good (B)
80 above: distinction (A)

Note: the output of your code should print the students Name, total score, grade and
short remark telling if the student is distinction or otherwise

I. Explain the procedures and steps to follow in solving the problem above
II. Write a constructive C++ code to justify your explanations in (I).
III. How can we solve a situation where by the user is having a Negative score (-
10) as the total score?

2. Write a program that mimics a calculator. The program should take as input two
integers and the operation to be performed. It should then output the numbers, the
operator, and the result.

SWITCH STATEMENTS:
An if else statement is great if you have one or two choices. But what happens when you have
several choices? You can still use it but switch statements are more preferable cause it makes
the code clean and easy to read.
A switch statements allow a variable to be tested for equality against a list of values. Each value
is called a case and the variable being switched on is checked for each case.

SYNTAX OF SWITCH STATEMENTS:


Switch (expression) {
Case expression1:
Statements…
Break;

Case expression2:
Statements…
Break;

Case expression3:
11
Statements…
Break;
.
.
.
Default:
Statements…

In C++, switch, case, break, and default are reserved words. In a switch structure, first the
expression is evaluated. The value of the expression is then used to perform the actions
specified in the statements that follow the reserved word case. The break keyword helps in
breaking the expression after it has been evaluated to true or false.

The switch statement executes according to the following rules:


1. When the value of the expression is matched against a case value (also called a label),
the statements execute until either a break statement is found or the end of the switch
structure is reached.
2. If the value of the expression does not match any of the case values, the statements
following the default label execute. If the switch structure has no default label and if
the value of the expression does not match any of the case values, the entire switch
statement is skipped.
3. A break statement causes an immediate exit from the switch structure.

Case Study 2:
1. Write C++ statements that output Male if the gender is 'M', Female if the gender is 'F',
and invalid gender otherwise.

2. Study the codes below and answer the following questions:

#include <iostream>
using namespace std;

int main()
{
int num;
cout << "Enter an integer between 0 and 7: "; //Line 1
cin >> num; //Line 2
cout << endl; //Line 3
cout << "The number you entered is "<<num<< endl; //Line 4

switch(num) //Line 5
{
case 0: //Line 6

12
case 1: //Line 7
cout << "Learning to use "; //Line 8
case 2: //Line 9
cout << "C++'s "; //Line 10
case 3: //Line 11
cout << "switch structure." << endl; //Line 12
break; //Line 13

case 4: //Line 14
break; //Line 15

case 5: //Line 16
cout << "This program shows the effect "; //Line 17
case 6: //Line 18
case 7: //Line 19
cout << "of the break statement." << endl; //Line 20
break; //Line 21

default: //Line 22
cout << "The number is out of range." << endl; //Line 23
}

cout << "Out of the switch structure." << endl; //Line 24


return 0;

I. Explain the concept of the program above


II. Extensively differentiate between IF-ELSE statements and SWITCH
III. What will be the output if the user key in 0,2,4 and 7 In different cases? Justify
IV. Explain The default keyword in (line 22) in respect to the code above and when will
the default statement be triggered?

LOOPING (Repetition):
The concept of looping is to allow a programmer to execute a block of code several Number
of times. In general, statements are executed sequentially: line 1 will run before line 2
continuously. Programming languages provided various control structures that allow for more
complicated execution paths.
A loop statements allows us to execute a statement or group of statements multiple times. The
following are type of loops found in C++ programming.
a. While loop
b. For loop
c. Do while loop
d. Nested loops

13
WHILE LOOP:
This executes a target statement(s) as long as a given condition is true. The syntax of a while
loop as follows:
While (condition){
Staments….
Increment or Decrement
}

Example:
Using while loop write a C++ program that prints the HOD’s name twenty (20) times.

FOR LOOP:
This is a shorthand of while loop, it allows a programmer to efficiently write a loop that
needs to execute a specific number of times. The syntax as follows:
for(initialization; condition; increment/){
staements…
}

Example:
Using for loops write a c++ program that prints the HOD’s name twenty (20) times.

DO-WHILE LOOPS:
Unlike for and while loops which test the loop condition at the top of the loop, the do-while
loop checks its condition at the bottom of the loop. A do-while loop is more similar to a while
loop except that a do-while loop is guaranteed to execute at least one time. The syntax as
follows:

do{
Statement(s)
Increment/Decrement
}
while (condition);

14
Notice that the conditional expression appears at the end of the loop, so the statement(s) in the
loop execute once before the condition is tested. If the condition is true, the flow of control
jumps back to execute the do statements until the condition is false.

Example:
Using a do-while loop write a C++ program that prints the HOD’s name twenty (20) times.

NB: We can create infinite loop knowingly or unknowingly. Infinite loop is loop that
has no ending. This occurs when a condition is always true so the statements will
keep executing till told otherwise.

ARRAYS:
Before formally defining an array, let us consider the following problem. We want to write a
C++ program that reads five numbers, finds their sum, and prints the numbers in reverse order.
previously, you learned how to read numbers, print them, and find the sum. The difference here
is that we want to print the numbers in reverse order. This means we cannot print the first four
numbers until we have printed the fifth, and so on. To do this, we need to store all of the
numbers before we start printing them in reverse order.

From what we have learned so far, the following program accomplishes this task:
#include <iostream>
using namespace std;
int main()
{
int item0, item1, item2, item3, item4;
int sum;
cout << "Enter five integers: ";
cin >> item0 >> item1 >> item2 >> item3 >> item4;
cout << endl;

sum = item0 + item1 + item2 + item3 + item4;


cout << "The sum of the numbers = " << sum << endl;

cout << "The numbers in the reverse order are: ";


cout << item4 << " " << item3 << " " << item2 << " "
<< item1 << " " << item0 << endl;

return 0;

15
This program works fine. However, if you need to read 100 (or more) numbers and print them
in reverse order, you would have to declare 100 variables and write many cin and cout
statements. Thus, for large amounts of data, this type of program is not desirable

Note the following in the previous program:


1. Five variables must be declared because the numbers are to be printed in reverse order.
2. All variables are of type int that is, of the same data type.
3. The way in which these variables are declared indicates that the variables to store these
numbers all have the same name except the last character, which is a number.

Statement 1 tells you that you have to declare five variables. Statement 3 tells you that it would
be convenient if you could somehow put the last character, which is a number, into a counter
variable and use one of the loops to count from 0 to 4 for reading and another for loop to count
from 4 to 0 for printing. Finally, because all variables are of the same type, you should be able
to specify how many variables must be declared and their data type with a simpler statement
than the one we used earlier. The data structure that lets you do all of these things in C++ is
called an array.

“An array is a collection of a fixed number of components all of the same data type. A one-
dimensional array is an array in which the components are arranged in a list form.”

The general Syntax of declaring one dataType arrayName[elements]


dimensional array:

Where elements are the total number of components in the Array and must be a constant
expression that evaluates to a positive integer.

Example
The statement
int num[5];

An array num of five components was declared. Each component is of type integer. The
components are num[0], num[1], num[2], num[3], and num[4]. Illustrate the
array num

16
ACCESSING ARRAY COMPONENTS:
The general syntax used in accessing array arrayName[indexNumber]
components is

in which indeNumber, called the index, is any expression whose value is a nonnegative integer.
The index value specifies the position of the component in the array.
In C++, [ ] is an operator called the array subscripting operator. Moreover, in C++, the array
index starts from 0

Example
1. Explain The diagram below in respect to C++ programming language and write the
source code

A. If int i = 4,

then the assignment statement: list[2 * i - 3] = 58; what will be the output
and why?

Case study 3:
Now that we know how to declare and process arrays, let us rewrite the program that we
discussed in the beginning of this chapter using Array concept. Recall that this program reads
five numbers, finds the sum, and prints the numbers in reverse order.

Review Questions:
1. Consider the following declaration: double salary[10]; In this declaration,
identify the following:
a. The array name.
b. The array size.
c. The data type of each array component.
d. The range of values for the index of the array.

2. What would be a valid range for the index of an array of size 50?
3. Write C++ statements to do the following:
a. Declare an array alpha of 15 components of type int.
b. Output the value of the tenth component of the array alpha.

17
c. Set the value of the fifth component of the array alpha to 35.
d. Set the value of the ninth component of the array alpha to the sum of the sixth
and thirteenth components of the array alpha.
e. Set the value of the fourth component of the array alpha to three times the value
of the eighth component minus 57.
f. Output alpha so that five components per line are printed.

4. Study the codes below and answer the following questions

int main()
{

int temp[5];
for (int i = 0; i < 5; i++)
temp[i] = 2 * i - 3;

for (int i= 0; i < 5; i++)


cout << temp[i] << " ";
cout << endl;

temp[0] = temp[4];
temp[4] = temp[1];
temp[2] = temp[3] + temp[0];

for (int i = 0; i < 5; i++)


cout << temp[i] << " ";
cout << endl;

return 0;

i. Explain the codes snippet above


ii. illustrate the output of the code above

UNDERSTANDING FUNCTIONS IN C++


A function is a group of statements that together perform a task. Every C++ program has at
least one function, which is main(), and all the most trivial programs can define additional
functions.

18
You can divide up your code into separate functions. How you divide up your code among
different functions is up to you, but logically the division usually is such that each function
performs a particular assignment.
A function declaration tells the compiler about a function's name, return type, and
parameters. A function definition provides the actual body of the function.

The C++ standard library provides numerous built-in functions that your program can call.
For example, function strcat() to concatenate two strings, function memcpy() to copy
one memory location to another location and many more functions.
A function is known with various names like a method or a sub-routine or a procedure etc.

DEFINING FUNCTIONS
To define a function in C++ you use the following syntax
return_type function_name (parameter list) {
body of the function…
}

I. Return Type: A function may return a value. The return_type is the data type of the
value the function returns. Some functions perform the desired operations without
returning a value. In this case, the return_type of that function is void.
II. Function Name: This is the actual name of the function. The function name and the
parameter list together constitute the function signature.
III. Parameters: A parameter is like a variable. When a function is invoked / called, you
key in a value to the parameter. This value is referred to as argument. The parameter
list refers to the type, order, and number of the parameters of a function. Parameters
are optional; that is, a function might not have any parameters and it is still valid
function.
IV. Function Body: The function body contains a collection of statements that define what
the function does.

EXAMPLE OF A FUNCTION:
Following is the source code for a function called max(). This function takes two parameters
num1 and num2 and return the biggest of both

int max(int num1, int num2) {

int result;

if (num1 > num2)


result = num1;
19
else
result = num2;

return result;
}

FUNCTION ARGUMENTS
If a function is to use arguments, it must declare variables that accept the values of the
arguments. These variables are called the formal parameters of the function.

The formal parameters behave like other local variables inside the function and are created
upon entry into the function and destroyed upon exit.

STRUCTURES (RECORDS):
Suppose that you want to write a program to process student data. A student record consists of,
among other things, the student’s name, student ID, GPA, courses taken, and course grades.
Thus, various components are associated with a student. However, these components are all of
different types. For example, the student’s name is a string, and the GPA is a floating-point
number. Because these components are of different types, you cannot use an array to group all
of the items associated with a student. C++ provides a structured data type called struct to group
items of different types. Grouping components that are related but of different types offers
several advantages.
“struct: A collection of a fixed number of components in which the components are
accessed by name. The components may be of different types”

Question:

1. List 5 advantages of grouping components that are related but of different


types?
2. Is it possible to group elements of the same type using struct? Justify
The components/elements of a struct are called the members of the struct. The general syntax
of a struct in C++ is:
struct structName
{
dataType1 identifier1;
dataType2 identifier2;
.
.
.
dataTypen identifiern;
};

20
Like any type definition, a struct is a definition, not a declaration. That is, it defines only a data
type; no memory is allocated. Once a data type is defined, you can declare variables of that
type. Let us first define a struct type, studentType, and then declare variables of that type.
struct studentType
{
string firstName;
string lastName;
char courseGrade;
int testScore;
int programmingScore;
double GPA;
};

//Instantiation Instantiation is a term mostly used in


studentType newStudent; structures. It is use to create instance
studentType student; of the structure created. Another name
of structure is derived data type
The statements above declare two struct
variables, newStudent and student, of type studentType. The memory allocated is large
enough to store firstName, lastName, courseGrade, testScore,
programmingScore, and GPA

ACCESSING STRUCTURE MEMBERS:


In arrays, you access a component by using the array name together with the relative position
(index) of the element. The array name and index are separated using square brackets. To
access a structure member, you use the struct variable name together with the member name;
these names are separated by a dot (period). The syntax for accessing a struct member is:

structVariableName.memberName

The structVariableName.memberName is just like any other variable. For example,


newStudent.courseGrade is a variable of type char, newStudent.firstName is a string variable,
and so on. As a result, you can do just about anything with struct members that you normally
do with variables. You can, for example, use them in assignment statements or input/output
(where permitted) statements.
In C++, the dot (.) is an operator called the member access operator. Suppose you want to initialize
the member GPA of newStudent to 0.0 The following statement accomplishes this task:
newStudent.GPA = 0.0; Similarly, the statements:

newStudent.firstName = "Muhammad";
newStudent.lastName = "Sani";

The statement:
cin >> newStudent.firstName;

21
reads the next string from the standard input device and stores it in:
newStudent.firstName

The statement:
cin >> newStudent.testScore >> newStudent.programmingScore;
reads two integer values from the keyboard and stores them in newStudent.testScore and
newStudent.programmingScore, respectively. Suppose that score is a variable of type int.
The statement:

score = (newStudent.testScore + newStudent.programmingScore) / 2;


assigns the average of newStudent.testScore and newStudent.programmingScore to score

ARRAYS IN STRUCTS:
Suppose a company has 50 full-time employees. We need to print their monthly paychecks and
keep track of how much money has been paid to each employee in the year-to-date.
First you need to define an employee’s record as follows:
struct employeeType
{
string firstName;
string lastName;
int personID;
string deptID;
double yearlySalary;
double monthlySalary;
double yearToDatePaid;
double monthlyBonus;
};

Each employee has the following members(properties): first name, last name, personal ID,
department ID, yearly salary, monthly salary, year-to-date paid, and monthly bonus. Because
we have 50 employees and the data type of each employee is the same, we can use an array of
50 components to process the employees’ data. Which is illustrated as follows:
employeeType employees[50];

NB: with the syntax above we avoided having 50 different instantiations and we can
proceed to manipulate the variables as we wish

In a nutshell structures are called derived data types because the user gets to create a datatype
of his wish and assign values, they are use in representing complex object with multiple
attributes.

22
Review Questions:
1. Define a struct, checkingAccount, to store the following data about a checking
account: account holder’s name, account number, balance, and the interest rate.
i. Using the structure definition above, declare a checkingAccount variable and
write C++ statements to store the following information: account holder’s
name—Fatima bukar, account number: 17328910, balance: 24476.38, interest
rate:2.5%.
ii. Define a struct, movieType, to store the following data about a movie: movie
name (string), movie director (string), producer (string), the year movie was
released (int), and number of copies in stock.

2. Create lecturer’s management system for computer engineering where all the following
information will be stored and manipulated
• First Name
• Last Name
• DOB
• fileID
• Rank
Note: A system Administrator should be able to key in and print out all the details from
a dedicated desktop. Make all the codes to be dynamic

CLASSES:
C++ provides another structured data type, called a class, which is specifically designed to
group data and functions. This chapter first introduces classes and explains how to use them
and then discusses the similarities and differences between a struct and a class.
In OOD (Object Oriented Design), the first step is to identify the components, called objects.
An object combines data and the operations on that data in a single unit. In C++, the mechanism
that allows you to combine data and the operations on that data in a single unit is called a
class. Now that you know how to store and manipulate data in computer memory and how
to construct your own functions, you are ready to learn how objects are constructed.
“A class is a collection of a fixed number of components. The components of a class are
called the members of the class”

The Generl Syntax to define a class: class classIdentifier


{
classMembersList
};

23
in which classMembersList consists of variable declarations and/or functions. That is, a
member of a class can be either a variable (to store data) or a function.

• If a member of a class is a variable, you declare it just like any other variable. Also, in
the definition of the class, you cannot initialize a variable when you declare it.
• If a member of a class is a function, you typically use the function prototype to declare
that member.
• If a member of a class is a function, it can (directly) access any member of the
classmember variables and member functions. That is, when you write the definition of
a member function, you can directly access any member variable of the class without
passing it as a parameter. The only obvious condition is that you must declare an
identifier before you can use it.

The members of a class are classified into three categories: private, public, and protected.
This chapter mainly discusses the first two types, private and public. In C++, private, protected,
and public are reserved words and are called member access specifiers. Following are some
facts about public and private members of a class:

• By default, all members of a class are private.


• If a member of a class is private, you cannot access it outside of the class declaration
scope
• A public member is accessible outside of the class declaration scope
• To make a member of a class public, you use the member access specifier public with
a colon, (:)
Suppose that we want to define a class to implement the time of day in a program. Because a
clock gives the time of day, let us call this class clockType. Furthermore, to represent time in
computer memory, we use three int variables: one to represent the hours, one to represent the
minutes, and one to represent the seconds.
Suppose these three variables are:
int hr;
int min;
int sec;

We also want to perform the following operations on the time:


1. Set the time.
2. Retrieve the time.
3. Print the time.
4. Increment the time by one second.
5. Increment the time by one minute.
6. Increment the time by one hour.
7. Compare the two times for equality.

24
To implement these seven operations, we will write seven functions: setTime(),
getTime(), printTime(), incrementSeconds(), incrementMinutes(),
incrementHours(), and equalTime(). From this discussion, it is clear that the class
clockType has 10 members: three member variables and seven member functions.

Some members of the class clockType will be private; others will be public. Deciding which
member to make public and which to make private depends on the nature of the member. The
general rule is that any member that needs to be accessed outside of the class is declared public;
any member that should not be accessed directly by the user should be declared private.
For example, the user should be able to set the time and print the time. Therefore, the members
that set the time and print the time should be declared public. Similarly, the members to
increment the time and compare the time for equality should be declared public. On the other
hand, to prevent the direct manipulation of the member variables hr, min, and sec, we will
declare them private.

NB: in most high-level programming Languages a member function is mostly referred as


the Method. Therefore, a function inside a class is called method

CREATING OBJECT:
Once a class is defined, you can declare variables of that type. In C++ terminology, a class
variable is called a class object or class instance.
The syntax for declaring a class object is the same as that for declaring any other variable. The
following statements declare two objects of type clockType:
clockType myClock;
clockType yourClock;

Accessing Class members:


Once an object of a class is declared, it can access all classObjectName.memberName
the members of the class. The general syntax for an
object to access a member of a class is:

Constructors:
To guarantee that the member variables of a class are initialized, you use constructors. There
are two types of constructors: with parameters and without parameters. The constructor without
parameters is called the default constructor. Constructors have the following properties:

• The name of a constructor is the same as the name of the class.


• A constructor, even though it is a function, has no return type. That is, it is neither a
value-returning function nor a void function.

25
• A class can have more than one constructor. However, all constructors of a class have
the same name.
• If a class has more than one constructor, the constructors must have different formal
parameter lists.
• Constructors execute automatically when a class object enters its scope. Because they
have no types, they cannot be invoked like other functions.

Invoking a constructor with parameter:


Suppose a class contains constructors with parameters. The syntax to invoke a constructor
with a parameter is:

className classObjectName(argument1, argument2, ...);

Note the following:

• The number of arguments and their type should match the formal parameters (in the
order given) of one of the constructors.
• If the type of the arguments does not match the formal parameters of any constructor
(in the order given), C++ uses type conversion and looks for the best match. Any
ambiguity will result in a compile-time error.

NB: a default constructor invoke itself without passing any arguments when the object of
class is created.

Destructors
Like constructors, destructors are also functions. Moreover, like constructors, a destructor does
not have a type. That is, it is neither a value-returning function nor a void function. However,
a class can have only one destructor, and the destructor has no parameters. The name of a
destructor is the tilde character (~), followed by the name of the class. For example, the name
of the destructor for the class clockType is: ~clockType();
A destructor automatically executes when the class object goes out of scope.

A Struct vs a Class:
A struct is a fixed collection of components, wherein the components can be of different types.
This definition of components in a struct included only member variables.
However, a C++ struct is very similar to a C++ class. As with a class, members of a struct can
also be functions, including constructors and a destructor. The only difference between a struct
and a class is that, by default, all members of a struct are public, and all members of a class are
private. You can use the member access specifier private in a struct to make a member private.

26
NB: Struct and classes are identically similar but not the same. Which means any
program you create using struct methodology can be mimic with class mechanism.

Review Question:
1. Study The codes and answer the questions below
class die
{
public:
die();

int roll();

int getNum() const;

private
int num;
};

i. Explain the code snippet above


ii. How many methods do we have from the code snippet and why?
iii. How can we access the private variable num

2. Find the syntax Error from the code snippet below


class BB
{
int one;
int two;
public:
bool equal(){

void BB();
}
3. Strictly using the concept of classes, create lecturer’s management system for computer
engineering where all the following information will be stored and manipulated
• First Name
• Last Name
• DOB
• fileID
• Rank
Note: A system Administrator should be able to key in and print out all the details from
a dedicated desktop. Make all the codes to be dynamic

27

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy