0% found this document useful (0 votes)
10 views66 pages

Module - Fundamental of Computing 1

The document outlines the course structure for 'Fundamentals of Computing 1' at Central Bicol State University of Agriculture, focusing on structured programming with C++. It includes topics such as C++ basics, control structures, functions, and data types, along with a detailed course calendar and assessment methods. The course also emphasizes hands-on sessions and the importance of understanding computer systems and programming concepts.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views66 pages

Module - Fundamental of Computing 1

The document outlines the course structure for 'Fundamentals of Computing 1' at Central Bicol State University of Agriculture, focusing on structured programming with C++. It includes topics such as C++ basics, control structures, functions, and data types, along with a detailed course calendar and assessment methods. The course also emphasizes hands-on sessions and the importance of understanding computer systems and programming concepts.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 66

Republic of the Philippines

CENTRAL BICOL STATE UNIVERSITY OF AGRICULTURE


San Jose, Pili, Camarines Sur 4418
ISO 9001:2015 www.cbsua.edu.ph
TÜV-R 01 100 1934918

COLLEGE OF ARTS AND SCIENCES


FUNDAMENTAL OF COMPUTING 1
Math 112

A. Course Overview

This course introduces the fundamental concepts of structured programming and provides a
comprehensive introduction to programming. Topics include basic of C++, basic data types,
control structures, functions, arrays, and the mechanics of running, testing, and debugging.
This course assumes computer literacy. In-class lectures and discussions are supplemented
by computer hands-on sessions.
Google Classroom Code:

B. Course Calendar

Week Covered Dates Topics Course Assessment


Online Quiz
 Fundamentals of Computer
Concepts
- Parts of Computer Systems
Data (information)
User
Hardware
1 Software

Introduction to computer
programming

2 Chapter 1 Basic of C++


Introduction C++
1.1Concept of C++
1.2OOPs Concept Basics
1.3Syntax and Structure of C++
program
1.4Data types in C++
3 1.5Variables in C++
1.6Operators in C++
1.7Sizeof operator in C++
1.8Loop Type

Chapter 2 Language Features


2.1Concept of C++ Features
4 2.2Difference between C and C++
2.3 Variables Declaration in C++
5

6 Chapter 3 C++ Overloading


(Function and Operator)
Republic of the Philippines
CENTRAL BICOL STATE UNIVERSITY OF AGRICULTURE
San Jose, Pili, Camarines Sur 4418
ISO 9001:2015 www.cbsua.edu.ph
TÜV-R 01 100 1934918

3.1 Concept of Overloading


7 3.2 Type of Overloading
3.3 Function Overloading in C++
8
9 Chapter 4 Inheritance
10 4.1 Concept of Inheritance
11 4.2 Multiple Inheritance

12 M I D T E R M
Chapter 5 Polymorphism in C++
13 5.1 Concept of Polymorphism
5.2 Importance of Polymorphism
14 5.3 Implementing Polymorphism
5.4 Other Application of
15 Polymorphism
5.5 Polymorphism Explanation

 Chapter 6 C++ Exception


16 Handling
6.1 Concept of Exception Handling
17 in C++ Programming

18 F I N A L S

C. Instructor

HERMENEGILDO JASON A. ASOR


Instructor 1

D. Course Assessments

Course Learning Competencies Being


Assessment Type Percentage Outcomes Being Due Date Assessed
Assessed Professional Transversal
Weeks 1 – 6 Examination 30% CO1, CO2, CO4, CO5 September 11 Critical
Weeks 7 – 12 Examination 35% CO1, CO3 October 30 In-depth Thinking
Republic of the Philippines
CENTRAL BICOL STATE UNIVERSITY OF AGRICULTURE
San Jose, Pili, Camarines Sur 4418
ISO 9001:2015 www.cbsua.edu.ph
TÜV-R 01 100 1934918

knowledge and
of ability to
Weeks 13 – 18 Examination 35% CO1, CO4, CO5 December 11 physiological express
processes technical
topics

WEEK 1
Introduction to VMGO, Course Outline, Grading System and the Subject
Introduction

The course will be initiated by discussing the core values of CBSUA to the students to the core. This
will involve PVMGOs and Quality Policy. The course outline, grading system, and class policies shall
also be introduced. Afterward, discussing of Fundamental of Computing and Introduction to
Computer Language. It is important to understand the relationship between the term’s programs,
programmers, and programming languages.

Learning Resources:
Republic of the Philippines
CENTRAL BICOL STATE UNIVERSITY OF AGRICULTURE
San Jose, Pili, Camarines Sur 4418
ISO 9001:2015 www.cbsua.edu.ph
TÜV-R 01 100 1934918

Computer
is a programmable, multiuse machine that accepts data, (raw, facts and figures)
and process or manipulates, it into information.

Computer Systems
a collection of entities(data, user, hardware, software and liveware) that are
designed to receive, process, manage and present information in a meaningful
format.

Data (information)
• Pieces of facts
• Computer organize and present information

Users
• People operating the computer
• Computer working for the people
• Users are most important part of computers
• Tell the computer what to do

Hardware
• Physical Components of the computer
• TANGIBLE (can be touched)

Software
 Step-by-step instructions to perform the task
 Also called a program
 INTANGIBLE (cannot be touched)
 Programs and software interchangeable terms
Republic of the Philippines
CENTRAL BICOL STATE UNIVERSITY OF AGRICULTURE
San Jose, Pili, Camarines Sur 4418
ISO 9001:2015 www.cbsua.edu.ph
TÜV-R 01 100 1934918

Major components of a computer


• INPUT DEVICES
• OUTPUT DEVICES
• CPU
• MEMORY
• STORAGE DEVICES

Input Devices
These devices allow user to enter the data into the computer.

Output Devices

Consist of devices that translate information processed by the


computer into human understandable format.

I/O Devices
• Some devices are both input as well as output devices.
• Can perform I/O simultaneously
• Touchpad Screens

CPU- Central Processing Unit

• Brain of the computer


• Two parts are:
• ALU (Arithmetic/Logical Unit)
• CU (Control Unit)

CPU- Control Unit

• Directs and coordinates flow of data through the CPU and


to other devices
Republic of the Philippines
CENTRAL BICOL STATE UNIVERSITY OF AGRICULTURE
San Jose, Pili, Camarines Sur 4418
ISO 9001:2015 www.cbsua.edu.ph
TÜV-R 01 100 1934918

• CPU instruction set is built to the Control Unit called Commands that a CPU can
execute.

CPU- Arithmetic Logic Unit

• a unit in a computer which carries out arithmetic and logical


operations.
Memory

 Two categories of Memory


- Volatile Memory
Loses its contents when the computer’s power is turned off
- Non-volatile Memory
Does not lose its contents when the computer’s power is off
• Stores Data or programs
(workspace or archiving/storage space)
• RAM: Random Access Memory (Volatile)
Stores current data and programs
More RAM results in a faster system
• ROM: Read Only Memory (non-volatile)
Permanent storage of programs/instructions
Holds the computer boot directions

Storage Devices

• Hold data and programs permanently


• Different from RAM
• Magnetic Storage; uses a magnet to access data
(Floppy ,Hard drive and USB drive)
• Optimal storage; uses a laser to access data
(CD and DVD drives)

Software

Computer software, or simply software, is a collection of data or


computer instructions that tell the computer how to work. This
is in contrast to physical hardware, from which the system is
built and actually performs the work.

Types of Software

• SYSTEM SOFTWARE
• APPLICATION SOFTWARE

System Software

• Enables the application to interact with the computer and manages the computer
Republic of the Philippines
CENTRAL BICOL STATE UNIVERSITY OF AGRICULTURE
San Jose, Pili, Camarines Sur 4418
ISO 9001:2015 www.cbsua.edu.ph
TÜV-R 01 100 1934918

internal resources.
- Operating System
- Device Drivers

Application Software

• It performs useful work on General-purpose task.


- Microsoft Office
- Antivirus

Utility Programs

• Utility Programs provide services not provided by the


system software.
• Usually used to recover the system, data or resources
Examples:
• Disk Defragmenter
• Data recovery Backup
• Virus protection

Types of Computers

1. Supercomputers
2. Mainframes
3. Minicomputers
4. Microcontrollers

Supercomputer
 Most powerful computers
 Physically largest in size
 Hundreds of thousands of processors that can process huge amounts of data
 Perform over 1 quadrillion calculations per second. e.g. IBM ASCI white
 Ideal for handling large and highly complex problems that require extreme calculating
power
Mainframe

 Mainly used by large organizations for critical application, typically bulk data
processing.
- Banks, Airlines, Insurance Companies
 Measured in millions of integer operations per second (MIPS)
 Vary in size from small, to medium, to large, depending on their use.
 Normally Dumb Terminals are connected to these main frames. Processing is done by
Mainframes.
Republic of the Philippines
CENTRAL BICOL STATE UNIVERSITY OF AGRICULTURE
San Jose, Pili, Camarines Sur 4418
ISO 9001:2015 www.cbsua.edu.ph
TÜV-R 01 100 1934918

Minicomputers

 Class of multi-user computers that lies in between mainframe computers (multi user)
and microcomputers or personal computers (single user)
 Midrange computer, such as the higher-end SPARC, POWER and Itanium-based
systems from sun microsystem, IBM and Hewlett-Packard

Six primary types of computers are designed to be used by one person at a time:

• Desktop computers
• Workstations
• Notebook (or laptop) computers
• Tablet computers
• Handheld computers
• Smart phones

DESKTOP COMPUTERS

The most common type of personal computer is the desktop computer—a


PC that is designed to sit on (or more typically under) a desk or table.

WORKSTATIONS

A workstation is a specialized, single-user computer that typically


has more power and features than a standard desktop PC. These
machines are popular among scientists, engineers, and animators
who need a system with greater-than-average speed and the power
to perform sophisticated tasks. Workstations often have large, high-
resolution monitors and accelerated graphics-handling capabilities,
making them suitable for advanced architectural or engineering design, modeling, animation,
and video editing.

NOTEBOOK COMPUTERS

Notebook computers, as their name implies, approximate the shape of a


writing notebook and easily fit inside a briefcase. Because people frequently
set these devices on their lap, they are also called laptops. Notebooks have a
“clam-shell” design; during use, the notebook’s lid is raised to reveal a thin
monitor and a keyboard. When not in use, the device folds up for easy storage.

TABLET PCS

The tablet PC is the newest development in portable, full-featured computers.


Tablet PCs offer all the functionality of a notebook PC, but they are lighter and
can accept input directly from a special pen—called a stylus or a digital pen—
or even the user’s fingers. Some of the newer models can display an image of a
Republic of the Philippines
CENTRAL BICOL STATE UNIVERSITY OF AGRICULTURE
San Jose, Pili, Camarines Sur 4418
ISO 9001:2015 www.cbsua.edu.ph
TÜV-R 01 100 1934918

keyboard on the screen and allow the user to type.

Learning Resources
1. CBSUA Website
2. Student Handbook
3. Fundamentals of Computing 1 (SY 2020-2021) Syllabus
4. Google.com
5. PowerPoint Presentation

Uploaded in this Google Drive Folder.

Tasks/Activities

• Lecture Discussion (Zoom/Google Meet) – Recorded


• PowerPoint Presentation
• Video Clips
• Quiz via google doc

Discussion Board

A Facebook group chat will be created where the students can discuss their ideas and thoughts. Chat
in Facebook Group allow us to communicate between users in a chat channel. Virtual Learning Portal
(VLP) will be the main source of lessons on the topic. This platform will be utilized throughout the
course.

Competency Checklist (Formative Assessment/Diagnostic)

The student will be assessed by filling out a questionnaire in google doc regarding the lessons that
have been presented. This assessment will determine the knowledge that they’ve learned with the
Video Lectures Presentation.
Instructions:

1. This is an individual activity.


2. Login to their institutional account
3. Check updated assessment

Tasks/Activities

• Answer the questionnaire


• Video presentation PowerPoint Presentation
• Video Clips
Republic of the Philippines
CENTRAL BICOL STATE UNIVERSITY OF AGRICULTURE
San Jose, Pili, Camarines Sur 4418
ISO 9001:2015 www.cbsua.edu.ph
TÜV-R 01 100 1934918

WEEK 2 and 3
Chapter 1 Basic of C++

Introduction

The course will be initiated by discussing the basic of C++, such as OOP’s Concept, syntax and
structure of C++, data types and variables in C++ programming language.

1.1.3 Benefits of C++ over C Language

The major difference being OOPS concept, C++ is an object-oriented language whereas C language is
a procedural language. Apart from this there are many other features of C++ which gives this
language an upper hand on C language.

Following features of C++ makes it a stronger language than C.

 There is Stronger Type Checking in C++


 All the OOPs features in C++ like Abstraction, Encapsulation, Inheritance etc. makes it more
worthy and useful for programmers.
 C++ supports and allows user defined operators(i.e Opearator Overloading) and function
overloading is also supported in it.
 Exception Handling in there in C++
 The concept of virtual functions and also constructors and destructor for objects.
 Inline functions in C++ instead of macros in C language. Inline functions make complete
function body act like Macro, safety.
 Variables can be declared anywhere in the program in C++, but must be declared before
they are used/

1.2 OOPS CONCEPT BASICS

Object Oriented programming is a programming style that is associated with the concept of Class,
Object and various other concepts revolving around these two, like Inheritance, Polymorphism,
Abstraction, Encapsulation etc.

Encapsulation

Polymorphism OOPS Inheritance

Abstraction
Republic of the Philippines
CENTRAL BICOL STATE UNIVERSITY OF AGRICULTURE
San Jose, Pili, Camarines Sur 4418
ISO 9001:2015 www.cbsua.edu.ph
TÜV-R 01 100 1934918

1.2.1 Access Control in Classes

Now before studying how to define class and its objects, lets first quickly learn what are access
specifies. Access specifies in C++ class defines the access control rules. C++ has 3 new keywords
introduce,

 Public
 Private
 Protected

This access specifies are used to set boundaries for availability of members of class be it data
members or member functions Access specifies in the program, are followed by a colon. You can use
either one, two or all 3 specifies in the same class to set different boundaries for different class
members. They change the boundary for all the declarations that follow them.

Public

-means all the class members declared under public will be available to everyone. The data members
and member functions declared public can be accessed by other classes too. Hence there are
chances that they might change them. So, the key members must not be declared public.

Private

-means that no one can access the class members declared private outside that class. If someone
tries to access the private member, they will get a compile time error. By default, class variables and
member functions are private.

Protected

-is the last access specified, and it is similar to private, it makes class member inaccessible outside
the class. But they can be accessed by any subclass of that class. (if class A is inherited by class B,
then class B is subclass of class A.

class Protected Access

protected: //protected access specifier

int x; //Data Member Declaration

void display (); // Member Function declaration

1.3 SYNTAX AND STRUCTURE OF C++ PROGRAM

Here we will discuss one simple and basic C++ program to print “Helo this is C++” and its structure in
parts with details and uses.
Republic of the Philippines
CENTRAL BICOL STATE UNIVERSITY OF AGRICULTURE
San Jose, Pili, Camarines Sur 4418
ISO 9001:2015 www.cbsua.edu.ph
TÜV-R 01 100 1934918

1.3.1 First C++ program

#include <iostream.h>

using namespace std;

int main()

cout << “Hello this is C++”;

Header files are included at the beginning just like in C programming. Here iostream is a header file
which provides us with input & output streams.

Using namespace std tells the compiler to use standard namespace. Namespace collects identifiers
used for class, object and variables. Namespace can be used by two ways in a program, either by the
use of using statement at the beginning, like we did in above mentioned program or by using name
of namespace as prefix befire the identifier with scope resolution (::) operator.

Example: std::cout << “A;

main() is the function which holds the executing part of program its return type is int.

cout<< is used to print anything in scree, same as printf in C language. cin and cout are the same as
scanf and printf, only difference is that you do not need to mention format specifiers like, %d for int
etc, in cout & cin.

Comments

For single line comments, use // before mentioning comment, like cout<<”single line”; // This is
single line comment

For multiple line comment, enclose the comment between /* and */

/* this is a multiple line comment */

Using Classes

Classes name must start with capital letter, and they contain data variables and member functions.
This is a mere introduction to classes,

class Abc

int i; // data variable

void display() //Member Function


Republic of the Philippines
CENTRAL BICOL STATE UNIVERSITY OF AGRICULTURE
San Jose, Pili, Camarines Sur 4418
ISO 9001:2015 www.cbsua.edu.ph
TÜV-R 01 100 1934918

{ Remember
cout <<”Inside Member Function”; Variables can be declared anywhere
} in the entire program, but must be
declared, before they are used.
}; // Class ends here Hence, we don’t need to declare
variable at the start of the program.

int main()

Abc obj; //Creating Abc class’s object

Obj.display(); //Calling member function using class object

This is how class is defined, its object is created and the member functions are used.

1.4 DATA TYPES IN C++

They are used to define type of variables and contents used. Data types define the way you use
storage in the programs you write. Data types can be built in or abstract.

Built in Data Types

These are the data types which are predefined and are wired directly into the compiler. Eg: int, char
etc.

User defined or Abstract data types

These are the type, that user creates as a class. In C++ these are classes where as in C it was
implemented by structures.

1.4.1 Basic Built in types

char Foe character storage (1byte)


Int For integral number (2bytes)
Float Single precision floating point (4bytes)
double Double precision floating point number (8bytes)

Example:

char a = ‘A’ ; //character type

int a = l; // integer type


Republic of the Philippines
CENTRAL BICOL STATE UNIVERSITY OF AGRICULTURE
San Jose, Pili, Camarines Sur 4418
ISO 9001:2015 www.cbsua.edu.ph
TÜV-R 01 100 1934918

float a = 3.14159; //floating point type

double a = 6e-4; // double type (e is for exponential)

Other Built in types

bool Boolean (true or false)


void Without any value
wchar_t Wide character

1.4.2 Enum as Data type

Enumerated type declares a new type-name and sequence of value containing identifiers which has
values starting from 0 and incrementing by 1 every time.

Modifiers

Specifiers modify the meaning of the predefined built-in data types and expand them to a much
larger set. There are four data type modifiers in C++, they are:

 Long
 Short
 Signed
 Unsigned

Below mentioned are some important points you must know about the modifiers.

 Long and short modify the maximum and minimum values that a data type will hold.
 A plain int must have a minimum size of short.
 Size hierarchy : short int <int <long int
 Size hierarchy for floating point numbers is : float <double <long double
 Long float is not a legal type and there are no short floating point numbers.
 Signed types includes both positive and negative numbers and is the default type.
 Unsigned numbers are always without any sign, that is always positive.

1.5 VARIABLES IN C++

Variable are used in C++, where we need storage for any value, which will change in program.
Variable can be declared in multiple ways each with different memory requirements and
functioning. Variable is the name of memory location allocated by the compiler depending upon the
data type of the variable.
Republic of the Philippines
CENTRAL BICOL STATE UNIVERSITY OF AGRICULTURE
San Jose, Pili, Camarines Sur 4418
ISO 9001:2015 www.cbsua.edu.ph
TÜV-R 01 100 1934918

Example: int i=10 // declared and initialized

Memory Location reserved


10 and is named as i

RAM

1.5.1 Basic types of Variables

Each variable while declaration must be given a datatype, on which the memory assigned to the
variable depends. Following are the basic types of variables,

Bool For variable to store Boolean values (true or false)


Char For variables to store character types
Int For variable with integral values
Float and double are also
type for variables with large
and floating point value

1.5.2 Declaration and Initialization

Variables must be declared before they are used. Usually it is preferred to declare them at the
starting of the program, but in C++ they can be declared in the middle of program too, but must be
done before using them.

Example :

int i; // declared but not initialized

char c;

int I, j, k; //Multiple declaration

initialization means assigning value to an already declared variable,

int I; // declaration

i = 10; // initialization

Initialization and declaration can be done in one single step also,

int i = 10; // initialization and declaration in same step

int i = 10, j=11;


Republic of the Philippines
CENTRAL BICOL STATE UNIVERSITY OF AGRICULTURE
San Jose, Pili, Camarines Sur 4418
ISO 9001:2015 www.cbsua.edu.ph
TÜV-R 01 100 1934918

if a variable is declared and not initialized by default it will hold a garbage value. Also, if a variable is
once declared and if try declare it again, we will get a compile time error.

int i,j;

i=10;

j=20;

int j=i+j; // compile time error, cannot redeclare a variable in same scope

1.5.3 Scope of Variables

All the variables have their area of functioning, and out of that boundary they don’t hold their value,
this boundary is called scope of the variable. For most of the cases its between the curly braces, in
which variable is declared that a variable exists, not outside it. We still study the storage classes
later, but as of now, we can broadly divide variables into two main types,

 Global Variables
 Local variables

Global variables

Global variables are those, which are once declared and can be used throughout the lifetime of the
program by any class or any function. They must be declared outside the main() function. If only
declared, they can be assigned different values at different time in program lifetime. But even if they
are declared and initialized at the same time outside the main() function, then also they can be
assigned any value at any point in the program.

Example: Only declared, not initialized

Include <iostream>

using namespace std;

int x; Global variable declared

int main()

x = 10; //initialized once

cout<<”first value of x = “<< x;

x=20; // initialized again

cout <<”Initialized again with valure = “ << x;

}
Republic of the Philippines
CENTRAL BICOL STATE UNIVERSITY OF AGRICULTURE
San Jose, Pili, Camarines Sur 4418
ISO 9001:2015 www.cbsua.edu.ph
TÜV-R 01 100 1934918

Local Variables

Local variables are the variables which exist only between the curly braces, in which its declared.
Outside that they are unavailable and leads to compile time error.

Example:

include <iostream>

using namespace std;

int main()

int i = 10;

if(1<20) // if condition scope starts

int n=100; // local variable declared and initialized

} // if condition scope ends

cout << n; //compile time error, n not available here

Some Special types of Variable

There are also some special keyword, to impart unique characteristics to the variables in the
program. Following two are mostly used,

 Final – once initialized, its value can’t be changed.


 Static – these variables hold their value between function calls.

Example:

#include<iostream.h>

using namespace std;

int main()

final int i=10;

static int y=20;

}
Republic of the Philippines
CENTRAL BICOL STATE UNIVERSITY OF AGRICULTURE
San Jose, Pili, Camarines Sur 4418
ISO 9001:2015 www.cbsua.edu.ph
TÜV-R 01 100 1934918

1.6 OPERATORS IN C++

Operators are special type of functions that takes one or more arguments and produces a new value.
For example: addition (+),

Subtraction (-), multiplication (*) etc., are all operators. Operators are used to perform various
operations on variables and constants.

1.6.1 Types of Operators

 Assignment Operator
 Mathematical Operators
 Relational Operators
 Logical Operators
 Bitwise Operators
 Shift Operators
 Unary Operators
 Ternary Operator
 Comma Operator

Assignment Operator (=)

Operates ‘=’ is used for assignment, it takes the right-hand side (called rvalue) and copy it into the
left-hand side (called lvalue). Assignment operator is the only operator which can be overloaded but
cannot be inherited.

Mathematical Operators

There are operator used to perform basic mathematical operations. Addition (+), Subtraction (-),
diversion(/) multiplication (*) and modulus(%) are the basic mathematical operators. Modulus
operator cannot be used with floating-point numbers.

C++ and C also use a shorthand notation to perform an operation and assignment at same type.
Example,

int x=10;

x +=4 // will add 4 to 10, and hence assign 14 to x .

x-+5 // will subtract 5 from 10 and assign 5 to x.

Relational Operators

These operators establish a relationship between operands. The relational operators are: less than
(<), greater than (>), less than or equal to (<=), greater than equal to (>=), equivalent (==) and not
equivalent (!=).

You must notice that assignment operator is (=) and there is a relational operator, for equivalent
(==). These two are different from each other, the assignment operator assigns the value to any
variable, whereas equivalent operator is used to compare values, life in if-else conditions,

Example
Republic of the Philippines
CENTRAL BICOL STATE UNIVERSITY OF AGRICULTURE
San Jose, Pili, Camarines Sur 4418
ISO 9001:2015 www.cbsua.edu.ph
TÜV-R 01 100 1934918

int x =10; //assignment operator

x=5; // again assignment operator

if(x == 5) // here we have used equivalent relational operator, for comparison

cout <<”Successfully compared”;

Logical Operators

The logical operators are AND (&&) and OR (||). They are used to combine two different expressions
together.

Bitwise Operators

There are used to change individual bits into a number. They work with only integral data types like
char, int and long and not with floating point values.

 Bitwise AND operators &


 Bitwise OR operator |
 And bitwise XOR operator ^
 And bitwise NOT operator ˜

They can be used as shorthand notation too, &=, |=, ^=, ˜= etc.

Shift Operators

Shift operators are used to shift Bits of any variables. It is of three types,

 Left Shift Operator <<


 Right Shift Operator >>
 Unsigned Right Shift Operator >>>

Unary Operators

These are the operators which work on only one operand. There are many unary operators, but
increment ++ and decrement - - operators are most used.

Other Unary Operators: address of & dereference *, new and delete bitwise not ˜, logical not !,
unary minus – and unary plus +.

Ternary Operator

The ternary if-else? : is an operator which has three operands.

int a = 10;

a > 5? Cout << “true” : cout << “false”

Comma operator
Republic of the Philippines
CENTRAL BICOL STATE UNIVERSITY OF AGRICULTURE
San Jose, Pili, Camarines Sur 4418
ISO 9001:2015 www.cbsua.edu.ph
TÜV-R 01 100 1934918

This is used to separate variables names and to separate expressions. In case expressions, the value
of last expression is produced and used.

Example:

int a,b,c; // variables declaration using comma operator

a=b++, c++; // a=c++ will be done.

1.7 SIZEOF OPERATOR IN C++

sizeOf is also an operator not a function, it is used to get information about the amount of memory
allocated for data types & Objects. It can be used to get size of user defined data types too. Sizeof
operator can be used with and without parentheses. cout << sizeof(double); //will print size of
double

int x=2;

int i=sizeOf x;

1.7.1 typedef Operator

typedef is a keyword used in C language to assign alternative names to existing types. Its mostly
used with user defined data types, when names of data types get slightly complicated. Following is
the general syntax for using typedef,

typedef existing_name alias_name

let’s take an example and see how typedef actually works.

typedef unsigned long ulong;

the above statement defines a term ulong for an unsigned long type. Now this ulong identifier can
be used to define unsigned long type variables.

Typedef and pointers

Again, the code inside the body of loop is executed and the value of ‘n’ becomes 2. When the value
of ‘n’ to 11. After this, the condition becomes false and the loop terminates.

typedef cab be used to give an alias name to pointers also. Here we have a case in which use of
typedef is beneficial during pointer declaration.

In pointers * binds to the right and not the left.

int* x,y;

by this declaration statement, we are actually declaring x as a pointer of type int, whereas y will be
declared as a plain integer.

1.8 LOOP TYPE


Republic of the Philippines
CENTRAL BICOL STATE UNIVERSITY OF AGRICULTURE
San Jose, Pili, Camarines Sur 4418
ISO 9001:2015 www.cbsua.edu.ph
TÜV-R 01 100 1934918

A computer is used for performing many repetitive types of tasks the process of repeatedly
performing tasks is known as looping. The statements in the block may be executed any number of
times from Zero to Up to the Condition is True. The loop is that in which a task is repeated until the
condition is true or we can say in the loop will Executes all the statements are until the given
condition is not to be false.

In the loop generally there three basic operations are performed

1. Initialization
2. Condition check
3. Increment

Playing with loops makes programming fun. Before we try to understand loop, you should be
thorough with all the previous topics of C++

Suppose, we have to print the first 10 natural numbers.

One way to do this is to print the first 10 natural numbers individually using cout. But what if you are
asked to print the first 100 natural numbers! You can easily do this with the help of loops.

1. While
2. do-while
3. for

all these are use for performing the repetitive tasks until the given conditions is not true.

1.8.1 While

While loop is known as Entry Controlled Loop because in the while loop first we initialize the value of
variable or starting point of execution and then we check the condition and if the condition is true
then it will execute the statements and then after it increments or decrements the value of a
variable. But in the while loop if a condition is false then it will never execute the statement so that
lets first look at the syntax of while loop.

while(condition)

Statement(s)

While loop checks whether the conditions written in () is true or not. If the condition is true, the
statements written in the body of the while loop i.e, inside the braces () are executed. These again
the condition is checked and found true, again the statements in the body of the while loop are
executed. This process continues until the condition becomes false.
Republic of the Philippines
CENTRAL BICOL STATE UNIVERSITY OF AGRICULTURE
San Jose, Pili, Camarines Sur 4418
ISO 9001:2015 www.cbsua.edu.ph
TÜV-R 01 100 1934918

Example

#include<iostream>

int main(){

using namespace std;

int n=1;

while ( n <= 10){

cout << n << endl

n++;

return 0;

Output

In our example, firstly we assigned a value 1 to a variable ‘n’. while (n <= 10) -checks the condition ‘n
<=10’. Since the value of n is 1 which is less than 10, the statements within the braces { } are
executed.

The value of ‘n’ i.e 1 is printed and n++ increases the value of ‘n’ by 1. So, now the value of ‘n’
becomes 2.

Now, again the condition is checked, this time also ‘n <=10’ is true because the value of ‘n’ is 2. So,
again the value of ‘n’ i.e 2 gets printed and the value of ‘n’ wo;; be increased to 3.

When the value of ‘n’ becomes 1-, again the condition ‘n <= 10’ is true and 10 gets printed for the
tenth time. Now, n++ increases the value to ‘n’ to 11.

This time, the condition ‘n <= 10’ becomes false and the program terminates.

Another example of while loop

#include <iostream>

int main(){

using namespace std;

int choice =1;

while ( choice == 1){

int a;

cout <<"Enter a number to check even or odd" << endl;

cin>> a; //input number

// check whether number is even or odd


Republic of the Philippines
CENTRAL BICOL STATE UNIVERSITY OF AGRICULTURE
San Jose, Pili, Camarines Sur 4418
ISO 9001:2015 www.cbsua.edu.ph
TÜV-R 01 100 1934918

if (a%2 == 0){

cout << "Your number is even" << endl;

else{

cout<<"Your number is odd"<< endl;

cout << "Want to check more : 1 for yes and 0 for no" << endl;

cin >> choice;

cout << "I hope you checked all your numbers" << endl;

return 0;

Output

Nesting of loops

Like ‘if/else’ we can also use one loop inside another. This is called nesting of loops. See this example
to make it clear.

#include<iostream>

int main (){

using namespace std;


Republic of the Philippines
CENTRAL BICOL STATE UNIVERSITY OF AGRICULTURE
San Jose, Pili, Camarines Sur 4418
ISO 9001:2015 www.cbsua.edu.ph
TÜV-R 01 100 1934918

int i;

int j;

for(i=12; i <= 14; i++) { /*outer loop*/

cout << “table of” << i << endl;

for(j=1; j <= 10; j++) { /*inner loop*/

cout << i << “*”<< j << “=” << (i*j) << endl;

return 0;

Output

When the first loop is executed, the value i is 12 and “Table of 12” gets printed. Now coming to the
second loop, the value of j is 1 and thus 12*1 =12 gets printed. In the second iteration of the inner
for loop, while the value of I is still 12, the value of j becomes 2 and thus 12 * 2 =24 gets printed.

Now coming to the second loop, the value of j is 1 and thus 12*1 12 gets
printed.
In the second iteration of the inner for loop, while the value of i is still 12, the
value of j becomes 2 and thus 12 * 2 = 24 gets printed. In the last iteration of
the inner for loop, the value of i is still 12 and the value of j becomes 10, thus
printing 12 * 10 = 120.
Now after all the iterations of the inner for loop are complete, there will be
the second iteration of the outer for loop increasing the value of i to 13 and
printing Table of 13. Again the inner for loop will be iterated with i equals 13.
We can use any loop inside any other loop according to the requirement. In
the above example, we used one for loop inside another.
Infinite Loop
There may exist some loops which can iterate r occur infinitely. These are
called Infinite p. These loops occur infinitely because their condition is always
true. We can make an infinite loop by leaving its conditional expression
empty (this is one of the many possible ways). When the conditional
expression is empty, it is assumed to be true. Lets see an example on how to
make a for loop infinite.
Republic of the Philippines
CENTRAL BICOL STATE UNIVERSITY OF AGRICULTURE
San Jose, Pili, Camarines Sur 4418
ISO 9001:2015 www.cbsua.edu.ph
TÜV-R 01 100 1934918

1.8.3 For loop


In This loop all the basic operations like initialization, condition checking and
incrementing or decrementing all these are performed in only one line. This is
similar to the while loop for performing its execution but only different in its
syntax.
Another type of loop is for loop.
Let's go to our first example in which we printed first 10 natural numbers
using while loop. We can also do this with for loop.
Let's look at the syntax of for loop.
for(initialization; condition; propagation)
{
statement(s)
}
#include <iostream>
int main(){
using namespace std;
int n;
for( n = 1; n <= 10; n++ ){
( cout <<n << endl;
}
return 0;
}
Output
1
2
3
4
5
6
7
8
9
10
Republic of the Philippines
CENTRAL BICOL STATE UNIVERSITY OF AGRICULTURE
San Jose, Pili, Camarines Sur 4418
ISO 9001:2015 www.cbsua.edu.ph
TÜV-R 01 100 1934918

Now let's see how for loop works.


for(n=1; n<=10; n++)
n=1 - This step is used to initialize a variable and is executed first and
only once. Here, 'n' is assigned a value 1.
n<=10 - This is a condition which is evaluated. If the condition is true, the
statements written in the body of the loop are executed. If it is false, the
statement just after the for loop is executed. This is similar to the condition
we used in <while> loop which was being
checked again and again.
n++ - This is executed after the code in the body of the for loop has been
executed. In this example, the value of <n> increases by 1 every time the
code in the body of for loop executes. There can be any expression here
which you want to run after every loop.
In the above example, firstly, ‘n=1’ assigns a value 1 to ‘n’,
Then the condition 'n<=10' is checked. Since the value of <n> is 1, therefore
the code in the body of for loop is executed and thus the current value of n
i.e., 1 gets printed.
Once the codes in the body of for loop are executed, step n++ is executed
which increases the value of n by 1. So now the value of 'n' is 2.
Again the condition 'n<=10' is checked which is true because the value of 'n'
is 2. Again, codes in the body of for loop are executed and 2 gets printed and
then the value of 'n' is again incremented When the value of 'n' becomes 10,
the condition 'n 10' is true and 10 gets printed. Now, when n++ increases the
lue to 'n to 11, the condition 'n<=10' becomes false and the loop terminates.
Don't you think it's just a different form of while loop? Yes, it is actually.

CASE STUDY
Real-World Applications of C++
1. Games:
C++ overrides the complexities of 3D games, optimizes resource
management and facilitates multiplayer with networking. The language is
extremely fast, allows procedural programming for CPU intensive functions
and provides greater control over hardware, because of which it has been
widely used in development of gaming engines. For instance, the science
fiction game Doom 3 is cited as an example of a game that used C++ well
and the Unreal Engine, a suite of game development tools, is written in C++
2. Graphic User Interface (GUI) based applications:
Many highly used applications, such as Image Ready, Adobe Premiere,
Photoshop and Illustrator, are scripted in C++.
3. Web Browsers:
With the introduction of specialized languages such as PHP and Java, the
adoption of C++ is limited for scripting of websites and web applications.
However, where speed and reliability are required, C++ is still preferred. For
instance, a part of Google's back-end is coded in C++, and the rendering
engine of a few open source projects, such as web browser Mozilla Firefox
and email client Mozilla Thunderbird, are also scripted in the programming
language.
4. Advance Computations and Graphics:
Republic of the Philippines
CENTRAL BICOL STATE UNIVERSITY OF AGRICULTURE
San Jose, Pili, Camarines Sur 4418
ISO 9001:2015 www.cbsua.edu.ph
TÜV-R 01 100 1934918

C++ provides the means for building applications requiring real time physical
simulations, high-performance image processing, and mobile sensor
applications. Maya 3D software, used for integrated 3D modeling, visual
effects and animation, is coded in C++
5. Database Software:
C++ and have been used for scripting MYSQL, one of the most popular
database management software. The software forms the backbone of a
variety of database-based enterprises, such as Google, Wikipedia, Yahoo and
YouTube etc.
6. Operating Systems:
C++ forms an integral part of many of the prevalent operating systems
including Apple's OS X and various versions of Microsoft Windows, and the
erstwhile Symbian mobile OS.
7. Enterprise Software:
C++ finds a purpose in banking and trading enterprise applications,
such as those deployed by Bloomberg and Reuters. It is also used in
development of advanced software, such as flight simulators and radar
processing
8. Medical and Engineering Applications:
Many advanced medical equipment, such as MRI machines, use C++
language for scripting their software. It is also part of engineering
applications, such as high-end CAD/CAM systems.
9. Compilers:
A host of compilers including Apple C++, Bloodshed Dev-C++, Clang C++
and MINGW make use of C++ language. C and its successor C++ are
leveraged for diverse software and platform development requirements, for
operating systems to graphic designing applications. Further, these
languages have assisted in the development of new languages for special
purposes like C, Java, PHP, Verilog etc.

Learning Resources:

CBSUA Website
Student Handbook
Fundamentals of Computing 1 (SY 2020-2021) Syllabus
Republic of the Philippines
CENTRAL BICOL STATE UNIVERSITY OF AGRICULTURE
San Jose, Pili, Camarines Sur 4418
ISO 9001:2015 www.cbsua.edu.ph
TÜV-R 01 100 1934918

Google.com
PowerPoint Presentation

Uploaded in this Google Drive Folder.

Discussion Board

A Facebook group chat will be created where the students can discuss their ideas and thoughts. Chat
in Facebook Group allow us to communicate between users in a chat channel. This platform will be
utilized throughout the course.

Competency Checklist

The student will be assessed by answering a questionnaire in this module regarding the lessons that
have been presented. This assessment will determine the knowledge that they’ve learned with the
Video Lectures Presentation.

Instructions:

1. This is an individual activity.


2. Login to their institutional account
3. Check updated assessment

KNOWLEDGE CHECK
Instruction : Circle the correct answer
1.The OOPs concept in C++, exposing only necessary information to users or
clients is known as
a. Abstraction
b. Encapsulation
c. Data hiding
d. Hiding complexity
2. Which of the following is an abstract
a. Class
b. Int
c. String
d. Double
3. Hiding the complexity is known
a. Abstraction
b. Encapsulation
c. Data hiding
d. Composition
4. For Cat and Animal class, correct way of inheritance is
a. class Cat: public Animal
b. class Animal: public Cat
c. Both are correct way
d. None is correct way
5. In a class, encapsulating an object of another class is called
a. Composition
Republic of the Philippines
CENTRAL BICOL STATE UNIVERSITY OF AGRICULTURE
San Jose, Pili, Camarines Sur 4418
ISO 9001:2015 www.cbsua.edu.ph
TÜV-R 01 100 1934918

b. Inheritance
c. Encapsulation
d. None

Tasks/Activities

• Answer the questionnaire


• Video presentation PowerPoint Presentation
• Video Clips

Week 4 and 5
Chapter 2 Language Features

Introduction
C++ is quite similar to C programming. In fact, C++ supports all
the features offered with C with the addition to various other important
Republic of the Philippines
CENTRAL BICOL STATE UNIVERSITY OF AGRICULTURE
San Jose, Pili, Camarines Sur 4418
ISO 9001:2015 www.cbsua.edu.ph
TÜV-R 01 100 1934918

features like object-oriented programming, operator overloading,


exception and error handling, the namespace feature, and many more.
We can say C++ is the advanced version of C programming. Features of
C++ give multiple reasons to upgrade our skills from C to C++.
 Multi-paradigm language: C++ is a language that supports
procedural, object-oriented and generic programming. This makes it
very versatile.
 Use of pointers and references: C+ supports pointers and
references that allow the user to deal directly with the memory and
gives all the control to the programmer.
This makes it very suitable for low-level tasks and very complex
projects.
 Statically Typed: A language is statically typed if the type of a
variable is known at compile time. For some languages, this means
that you as the programmer must specify what type each variable
is. The main advantage here is that all kinds of checking can be
done by the compiler, and therefore a lot of trivial bugs are caught
at a very early stage.
 C++ allows you to specify more than one definition for an operator
for different types (objects?) which is called operator overloading.
This allows users to treat even very complex types as built-in types.
 An interface describes the behavior or capabilities of a C++ class
without committing to a particular implementation of that class. The
C# interfaces are implemented using abstract classes and these
abstract classes should not be confused with data abstraction which
is a concept of keeping implementation details separate from
associated data.
 Multiple Inheritance is a feature of C++ where a class can inherit
from more than one classes. The constructors of inherited classes
are called in the same order in which they are inherited. The
destructors are called in reverse order of constructors. Multiple
inheritances allow the object to be of multiple types and hence
makes real-world modeling in the program very easy.
 Using ternary operators as values
 The auto keyword that does type deduction automatically without
needing the programmer to interfere.

2.1 CONCEPT OF C++ FEATURES

Here are some of the remarkable features of C++ language:


Republic of the Philippines
CENTRAL BICOL STATE UNIVERSITY OF AGRICULTURE
San Jose, Pili, Camarines Sur 4418
ISO 9001:2015 www.cbsua.edu.ph
TÜV-R 01 100 1934918

1. OOP (Object-Oriented Programming)

C++ is an object-oriented language, unlike C which is a procedural


language. This is one of the most important features of C++. It employs
the use of objects while programming. These objects help you implement
real-time problems based on data abstraction, data encapsulation, data
hiding, and polymorphism. We have briefly discussed all the 5 main
concepts of object-oriented programming.
The OOP concepts are:

 Data abstraction: Data abstraction is an act of representing


the important features of data without including the background
details or the method applied to obtain it.
 Data encapsulation: Data encapsulation is nothing but a
process to implement data abstraction by wrapping up the data
and functions into an exclusive block.
 Inheritance: The term inheritance refers to transferring the
properties of the parent class to the child class. We can
implement the basic idea of inheritance by creating more than
one class, which we formally refer to as derived classes by
linking them with what we call the base class. This concept
reduces the redundancy of the program and makes it easy to
transfer/copy the properties of one class to another
 Data hiding: Data hiding refers to protecting data from
unauthorized access. It is basically responsible for securing the
data. It is important to note that data encapsulation is different
from data hiding as encapsulation mainly focuses on shifting the
focus on important data than explaining its complex nature.
 Polymorphism: The word poly means ‘many’ and morphism
means ‘forms’. Clearly, polymorphism refers to displaying that
data in more than one form.
Republic of the Philippines
CENTRAL BICOL STATE UNIVERSITY OF AGRICULTURE
San Jose, Pili, Camarines Sur 4418
ISO 9001:2015 www.cbsua.edu.ph
TÜV-R 01 100 1934918

2. Platform or Machine Independent/ Portable

In simple terms, portability refers to using the same piece of code in


varied environments.

Let us understand this C++ feature with the help of an example. Suppose
you write a piece of code to find the name, age, and salary of an
employee in Microsoft Windows and for some apparent reason you want
to switch your operating system to LINUX. This code will work in a similar
fashion as it did in Windows.

3. Simple

When we start off with a new language, we expect to understand in depth.


The simple context of C++ gives an appeal to programmers, who are
eager to learn a new programming language.
If you are already familiar with C, then you don’t need to worry about
facing any trouble while working in C++. The syntax of C++ is almost
similar to that of C. Afterall C++ is referred to as “C with classes”.

4. High-level programming language

It is important to note that C++ is a high-level programming language,


unlike C which is a mid-level programming language. It makes it easier for
the user to work in C++ as a high-level language as we can closely
associate it with the human-comprehensible language, that is, English.

5. Popular

After learning C, it is the base language for many other popular


programming languages which supports the feature of object-oriented
Republic of the Philippines
CENTRAL BICOL STATE UNIVERSITY OF AGRICULTURE
San Jose, Pili, Camarines Sur 4418
ISO 9001:2015 www.cbsua.edu.ph
TÜV-R 01 100 1934918

programming. Bjarne Stroustrup found Simula 67, the first object-oriented


language ever, lacking simulations and decided to develop C++.

6. Case sensitive

Just like C, it is pretty clear that the C++ programming language treats
the uppercase and lowercase characters in a different manner. For
instance, the meaning of the keyword ‘cout’ changes if we write it
as ‘Cout’ or “COUT”. Other programming languages like HTML and
MySQL are not case sensitive.
7. Compiler-Based

Unlike Java and Python that are interpreter-based, C++ is a compiler


based language and hence it a relatively much faster than Python and
Java.

Get a complete guide to master in Python Programming


Language
8. DMA (Dynamic Memory Allocation)

Since C++ supports the use of pointers, it allows us to allocate memory


dynamically. We may even use constructors and destructors while
working with classes and objects in C++.

9. Existence of Libraries

The C++ programming language offers a library full of in-built functions


that make things easy for the programmer. These functions can be
accessed by including suitable header files.

10. Speed

As discussed earlier, C++ is compiler-based hence it is much faster than


other programming languages like Python and Java that are interpreter-
based.

2.2 Difference between C and C++

C C++

C was developed by Dennis Ritchie C++ was developed by Bjarne


between 1969 and 1973 at AT&T Stroustrup in 1979 with C++'s
Bell Labs. predecessor "C with Classes".

When compared to C++, C is a C++ is a superset of C. C++ can


subset of C++. run most of C code while C cannot
run C++ code.
Republic of the Philippines
CENTRAL BICOL STATE UNIVERSITY OF AGRICULTURE
San Jose, Pili, Camarines Sur 4418
ISO 9001:2015 www.cbsua.edu.ph
TÜV-R 01 100 1934918

C supports procedural programming C++ supports both procedural and


paradigm for code development. object-oriented programming
paradigms; therefore, C++ is also
called a hybrid language.

C does not support object-oriented Being an object-oriented


programming; therefore it has no programming language C++
support for polymorphism, supports polymorphism,
encapsulation, and inheritance. encapsulation, and inheritance.

In C (because it is a procedural In C++ (when it is used as object-


programming language), data and oriented programming language),
functions are separate and free data and functions are
entities. encapsulated together in form of
an object. For creating objects class
provides a blueprint of structure of
the object.

In C, data are free entities and can In C++, Encapsulation hides the
be manipulated by outside code. data to ensure that data structures
This is because C does not support and operators are used as
information hiding. intended.

C, being a procedural programming, While, C++, being an object


it is a function driven language. oriented programming, it is an
object driven language.

C does not support function and C++ supports both function and
operator overloading. operator overloading.

C does not allow functions to be In C++, functions can be used


defined inside structures. inside a structure.

C does not have namespace C++ uses NAMESPACE which avoid


feature. name collisions.
A namespace is a declarative
region that provides a scope to the
identifiers (the names of types,
functions, variables, etc) inside it.
Namespaces are used to organize
code into logical groups and to
prevent name collisions that can
occur especially when your code
Republic of the Philippines
CENTRAL BICOL STATE UNIVERSITY OF AGRICULTURE
San Jose, Pili, Camarines Sur 4418
ISO 9001:2015 www.cbsua.edu.ph
TÜV-R 01 100 1934918

base includes multiple libraries. All


identifiers at namespace scope are
visible to one another without
qualification. Identifiers outside the
namespace can access the
members by using the fully
qualified name for each identifier.

C uses functions for input/output. C++ uses objects for input output.
For example scanf and printf. For example cin and cout.

C does not support reference C++ supports reference variables.


variables.

C has no support for virtual and C++ supports virtual and friend
friend functions. functions.

C C++ provides new operator for


provides malloc() and calloc() functi memory allocation
ons for dynamic memory allocation, and delete operator for memory de-
and free() for memory de-allocation. allocation.

C does not provide direct support C++ provides support for exception
for error handling (also called handling. Exceptions are used for
exception handling) "hard" errors that make the code
incorrect.

Key Differences Between C Vs C++


Enlisted below are the main differences between C Vs C++.

#1) Type of Programming:


C is a procedural language in which the program revolves around the
functions. The entire problem is broken down into numerous functions.
The main focus of the program is on functions or procedures to get the
things done.

C++, on the contrary, is an object-oriented programming language. Here


the data of the problem is the main focus and the classes are built around
this data. Functions operate on the data and closely bound to data.

#2) Programming Approach:


Republic of the Philippines
CENTRAL BICOL STATE UNIVERSITY OF AGRICULTURE
San Jose, Pili, Camarines Sur 4418
ISO 9001:2015 www.cbsua.edu.ph
TÜV-R 01 100 1934918

As C is a procedural language, it follows a top-down approach of


programming. Here we take the problem and then break it into
subproblems until we find single subproblems that can be solved directly.
Then we combine the solutions to get the main solution.

C++ follows a bottom-up approach to programming. In this, we start with


low-level design or coding and then build on this low-level design to get a
high-level solution.

#3) Application Development:


C language is helpful in the programming of embedded systems or low-
level implementations.

C++, on the other hand, is more suitable for server-side applications,


network applications or for applications like gaming, etc.

#4) File Extension:


The programs written in C are usually saved with “.c” extension while the
C++ programs are saved with the “.cpp” extension.

#5) Compatibility With Each Other:


C++ is a subset of C as it is developed and takes most of its procedural
constructs from the C language. Thus any C program will compile and run
fine with the C++ compiler.

However, C language does not support object-oriented features of C++


and hence it is not compatible with C++ programs. Therefore programs
written in C++ will not run on C compilers.

#6) Compatibility With Other Languages:


C++ language is generally compatible with other generic programming
languages but C language is not.

#7) Ease of Coding:


We can say that C is a hands-on language and we can program it in
whichever way we want. C++ consists of some high-level object-oriented
programming constructs that help us to code high-level programs.

Thus if we say C is easy then C++ is also easier to code.

#8) Data Security:


In C, the main emphasis is on functions or procedures rather than on data.
Hence as far as data security is concerned, it is negligible in C.
Republic of the Philippines
CENTRAL BICOL STATE UNIVERSITY OF AGRICULTURE
San Jose, Pili, Camarines Sur 4418
ISO 9001:2015 www.cbsua.edu.ph
TÜV-R 01 100 1934918

In C++, as we are dealing with classes and objects, the main building
block of the program is Data. Thus, data is tightly secured using classes,
access specifiers, encapsulation, etc.

#9) Program Division:


A program in C is divided into functions and modules. These functions and
modules are then called by the main function or other functions for
execution.

A C++ program is divided into classes and objects. The problem is


designed into classes and the objects of these classes are the executing
units that are created by the main functions and are executed.

#10) Standard I/O Operations:


The standard input-output operations in C to read/write data from/to the
standard device are ‘scanf’ and ‘printf’ respectively.

In C++, the data is read from the standard input device using ‘cin’ while it
is printed to the output device using ‘cout’.

#11) Focus/Emphasis:
Being a procedural language, C has more emphasis on the sequence of
steps or procedures to solve a problem.

C++, on the other hand, is object-oriented and thus puts more focus on
objects and classes around which the solution is to be built.

#12) The main() Function:


In C++ we cannot call a main() function from any other point. The main()
function is the single execution point.

However, in C language, we can have a main() function called by the


other functions in the code.

#13) Variable:
Variables need to be declared at the beginning of the function block in C,
on the contrary, we can declare variables anywhere in a C++ program
provided they are declared before they are used in the code.

#14) Global Variables:


C language allows multiple declarations of global variables. C++,
however, doesn’t allow multiple declarations of global variables.

#15) Pointers And Reference Variables:


Republic of the Philippines
CENTRAL BICOL STATE UNIVERSITY OF AGRICULTURE
San Jose, Pili, Camarines Sur 4418
ISO 9001:2015 www.cbsua.edu.ph
TÜV-R 01 100 1934918

Pointers are the variables that point to memory addresses. Both C and C+
+ support pointers and various operations performed on pointers.

References act as aliases for the variables and point to the same memory
location as a variable.

C language only supports pointers and not references. C++ supports


pointers as well as references.

#16) Enumerations:
We can declare enumerations in C as well as C++. But in C, the
enumeration constants are of Integer type. It is the same as declaring an
integer constant without any type of safety.

In C++, the enumerations are different. They are of distinct types. Thus to
assign an integer type to a variable of an enumerated type, we need
explicit type conversion.

However, we can assign an enumerated value to a variable of integer type


as enumerated type allows integral promotion or implicit conversion.

#17) Strings:
As far as strings are concerned, the declaration ‘char []’ declares a string
array. But when the string declared as above is passed between the
functions, then there is no guarantee that it will not be changed by the
other external functions as these strings are mutable.

This drawback is not there in C++ as C++ supports string data type that
defines immutable strings.

#18) Inline Function:


Inline functions are not supported in C. C usually works with macros to
speed up the execution. In C++ on the other hand, inline functions, as
well as macros, are used.

#19) Default Arguments:


Default arguments/parameters are used when the parameters are not
specified at the time of the function call. We specify default values for
parameters in the function definition.

The C language does not support default parameters. Whereas C++


supports the use of default arguments.

#20) Structures:
Republic of the Philippines
CENTRAL BICOL STATE UNIVERSITY OF AGRICULTURE
San Jose, Pili, Camarines Sur 4418
ISO 9001:2015 www.cbsua.edu.ph
TÜV-R 01 100 1934918

Structures in C and C++ use the same concept. But the difference is, in C,
as we cannot include functions as members.

C++ allows structures to have functions as its members.

#21) Classes & Objects:


C is a procedural language and hence it does not support the concept of
classes and objects.

On the other hand, C++ supports the concept of classes and objects and
almost all the applications in C++ are built around classes and objects.

#22) Data Types:


C supports built-in and primitive data types. Contrary to this, C++
supports user-defined data types in addition to built-in and primitive data
types.

Apart from this C++ also supports Boolean and string data types which
are not supported by C.

#23) Function Overloading:


Function overloading is the ability to have more than one function with the
same name but different parameters or a list of parameters or order of
parameters.

This is an important feature of object-oriented programming and is


present in C++. However, C does not support this feature.

#24) Inheritance:
Inheritance is also an important feature of object-oriented programming
that is supported by C++ and not C.

#25) Functions:
C does not support functions with default arrangements like default
parameters etc. C++ supports functions with default arrangements.

#26) Namespace:
Namespaces are not supported in C but are supported by C++.
#27) Source Code:
C is a free-format language that gives us the ability to program anything.
C++ is derived from C and also has object-oriented programming features
which make it more efficient as far as the source code is concerned.

#28) Abstraction:
Republic of the Philippines
CENTRAL BICOL STATE UNIVERSITY OF AGRICULTURE
San Jose, Pili, Camarines Sur 4418
ISO 9001:2015 www.cbsua.edu.ph
TÜV-R 01 100 1934918

Abstraction is the way to hide the implementation details and expose only
the required interface to the user. This is one of the distinguishing
features of Object-oriented programming.

C++ supports this feature while C does not.

#29) Encapsulation:
Encapsulation is a technique using which we encapsulate the data from
the outside world. This aids in information hiding.

C++ uses classes which bundle data and the functions operating on this
data in a single unit. This is encapsulation. C does not have this feature.

#30) Information Hiding:


The features of abstraction and encapsulation can aid in information
hiding by exposing only the required details and hiding the details like
implementation, etc., from the user. This way we can enhance the
security of data in our programs.

C++ puts great emphasis on data and uses abstraction and encapsulation
for information hiding.

C doesn’t put any emphasis on data and does not deal with information
hiding.

#31) Polymorphism:
Polymorphism simply means that one object has many forms and it is an
essential feature of object-oriented programming. Being an object-
oriented language, C++ supports polymorphism.

C has no support for object-oriented programming and does not support


polymorphism. However, we can simulate the dynamic dispatch of
functions in C using function pointers.

#32) Virtual Function:


Virtual functions which are also called as Runtime polymorphism is a
technique that is used to resolve function calls at runtime. This is yet
another feature of object-oriented programming which is supported by C+
+ and not by C.

#33) GUI Programming:


For programming related to GUI (Graphical User Interface), C uses Gtk
tools while C++ uses Qt tools.
Republic of the Philippines
CENTRAL BICOL STATE UNIVERSITY OF AGRICULTURE
San Jose, Pili, Camarines Sur 4418
ISO 9001:2015 www.cbsua.edu.ph
TÜV-R 01 100 1934918

#34) Mapping:
As far as the mapping of data with functions is concerned, C language is
very complicated as it does not keep any focus on data.

Whereas C++ has a good mapping of data and functions as it supports


classes and objects that bind data and functions together.

#35) Memory Management:


Both C and C++ have manual memory management but how memory
management is done is different in both languages.

In C we use functions like malloc (), calloc (), realloc (), etc., to allocate
memory and free () function to free the memory. But, in C++, we use new
() and delete () operators to allocate and deallocate the memory
respectively.

#36) Default Headers:


Default headers contain the common function calls that are used in
programming languages mainly for input-output etc.

In C, ‘stdio.h’ is the default header used while C++ uses <iostream> as


the default header.
#37) Exception/Error Handling:
C++ supports exception/error handling using the try-catch blocks. C
doesn’t support exception handling directly but we can handle errors
using some workaround.

#38) Keywords:
C++ supports a lot more keywords than that of C. In fact, C has only 32
keywords whereas C++ has 52 keywords.

#39) Templates:
Templates allow us to define classes and objects independent of the data
type. Using templates, we can write generic code and call it for any data
type.

C++ being object-oriented uses classes and objects and thus supports
templates. C, on the other hand, doesn’t support the concept of
templates.
Republic of the Philippines
CENTRAL BICOL STATE UNIVERSITY OF AGRICULTURE
San Jose, Pili, Camarines Sur 4418
ISO 9001:2015 www.cbsua.edu.ph
TÜV-R 01 100 1934918

Tabular Format: C Vs C++


N
Characteristics C C++
o

1 Type of Procedural language Object-Oriented programming


programming language.

2 Programming Top-down approach Bottom-up approach


Approach

3 Application Good for embedded Good for networking, server-side


development devices, system-level applications, gaming, etc.
coding etc.

4 File Extension .c .cpp

5 Compatibility Not Compatible with Compatible with C as C++ is a


with each other C++. subset of C.

6 Compatibility Not compatible Compatible


with other
languages

7 Ease of coding Allows us to code Comes with highly advanced


everything. Object-Oriented concepts.

8 Data Security Negligible High

9 Program division Program divided into Program divided into classes and
functions. objects.

10 Standard I/O scanf/printf cin/cout


operations

11 Focus/emphasis Emphasizes on Emphasizes on data rather than


functions and/or functions.
processes.

12 The main() Can call main through Not possible to call main from any
Republic of the Philippines
CENTRAL BICOL STATE UNIVERSITY OF AGRICULTURE
San Jose, Pili, Camarines Sur 4418
ISO 9001:2015 www.cbsua.edu.ph
TÜV-R 01 100 1934918

N
Characteristics C C++
o

function other functions. point.

13 Variables To be declared at the Can be declared anywhere in the


beginning of the program.
function.

14 Global variables Multiple declarations No multiple declarations.

15 Reference Only Pointers Both


Variables and
pointers

16 Enumerations Only integer types. Distinct type

17 Strings Supports only char[] Supports string class which is


immutable.

18 Inline function Not supported Supported

19 Default Not supported Supported


arguments

20 Structures Cannot have functions Can have functions as structure


as structure members. members.

21 Classes and Not supported Supported


Objects

22 Data Types Only built-in and Boolean and string types


primitive data types supported in addition to built-in
are supported. data types.
No Boolean and string
types.

23 Function Not supported Supported


overloading
Republic of the Philippines
CENTRAL BICOL STATE UNIVERSITY OF AGRICULTURE
San Jose, Pili, Camarines Sur 4418
ISO 9001:2015 www.cbsua.edu.ph
TÜV-R 01 100 1934918

N
Characteristics C C++
o

24 Inheritance Not supported Supported

25 Functions Does not support Supports functions with default


functions with default arrangements.
arrangements.

26 Namespace Not supported Supported

27 Source code Free-format Originally taken from C plus object-


oriented.

28 Abstraction Not present Present

29 Information Not supported Supported


hiding

30 Encapsulation Not supported Supported

31 Polymorphism Not supported Supported

32 Virtual function Not supported Supported

33 GUI programming Using the Gtk tool. Using the Qt tools.

34 Mapping Cannot easily map data Data and functions can be easily
and functions. mapped.

35 Memory Malloc(), calloc(), free() New() and delete() operators.


management functions.

36 Default headers Stdio.h iostream header

37 Exception/error No direct support. Supported


handling
Republic of the Philippines
CENTRAL BICOL STATE UNIVERSITY OF AGRICULTURE
San Jose, Pili, Camarines Sur 4418
ISO 9001:2015 www.cbsua.edu.ph
TÜV-R 01 100 1934918

N
Characteristics C C++
o

38 Keywords Supports 32 keywords. Supports 52 keywords.

39 Templates Not supported Supported

2.3 VARIABLES DECLARATION IN C++


A variable provides us with named storage that our programs can
manipulate. Each variable in C++ has a specific type, which determines
the size and layout of the variable's memory; the range of values that
can be stored within that memory; and the set of operations that can be
applied to the variable.
The name of a variable can be composed of letters, digits, and the
underscore character. It must begin with either a letter or an underscore.
Upper and lowercase letters are distinct because C++ is case-sensitive −

Sr.No Type & Description

1
bool
Stores either value true or false.

2
char
Typically a single octet (one byte). This is an integer type.

3
int
The most natural size of integer for the machine.

4
float
A single-precision floating point value.

5
double
A double-precision floating point value.

6
void
Republic of the Philippines
CENTRAL BICOL STATE UNIVERSITY OF AGRICULTURE
San Jose, Pili, Camarines Sur 4418
ISO 9001:2015 www.cbsua.edu.ph
TÜV-R 01 100 1934918

Represents the absence of type.

7
wchar_t
A wide character type.

C++ also allows to define various other types of variables, which we will
cover in subsequent chapters like Enumeration, Pointer, Array,
Reference, Data structures, and Classes.
Following section will cover how to define, declare and use various types
of variables.
Variable Definition in C++
A variable definition tells the compiler where and how much storage to
create for the variable. A variable definition specifies a data type, and
contains a list of one or more variables of that type as follows −
type variable_list;
Here, type must be a valid C++ data type including char, w_char, int,
float, double, bool or any user-defined object, etc.,
and variable_list may consist of one or more identifier names separated
by commas. Some valid declarations are shown here −
int i, j, k;
char c, ch;
float f, salary;
double d;
The line int i, j, k; both declares and defines the variables i, j and k;
which instructs the compiler to create variables named i, j and k of type
int.
Variables can be initialized (assigned an initial value) in their declaration.
The initializer consists of an equal sign followed by a constant expression
as follows −
type variable_name = value;
Some examples are −
extern int d = 3, f = 5; // declaration of d and f.
int d = 3, f = 5; // definition and initializing d and f.
byte z = 22; // definition and initializes z.
char x = 'x'; // the variable x has the value 'x'.
For definition without an initializer: variables with static storage duration
are implicitly initialized with NULL (all bytes have the value 0); the initial
value of all other variables is undefined.
Republic of the Philippines
CENTRAL BICOL STATE UNIVERSITY OF AGRICULTURE
San Jose, Pili, Camarines Sur 4418
ISO 9001:2015 www.cbsua.edu.ph
TÜV-R 01 100 1934918

Variable Declaration in C++


A variable declaration provides assurance to the compiler that there is
one variable existing with the given type and name so that compiler
proceed for further compilation without needing complete detail about
the variable. A variable declaration has its meaning at the time of
compilation only, compiler needs actual variable definition at the time of
linking of the program.
A variable declaration is useful when you are using multiple files and you
define your variable in one of the files which will be available at the time
of linking of the program. You will use extern keyword to declare a
variable at any place. Though you can declare a variable multiple times
in your C++ program, but it can be defined only once in a file, a function
or a block of code.
Example
Try the following example where a variable has been declared at the top,
but it has been defined inside the main function −
#include <iostream>
using namespace std;

// Variable declaration:
extern int a, b;
extern int c;
extern float f;

int main () {
// Variable definition:
int a, b;
int c;
float f;

// actual initialization
a = 10;
b = 20;
c = a + b;

cout << c << endl ;

f = 70.0/3.0;
cout << f << endl ;

return 0;
}
When the above code is compiled and executed, it produces the following
result −
Republic of the Philippines
CENTRAL BICOL STATE UNIVERSITY OF AGRICULTURE
San Jose, Pili, Camarines Sur 4418
ISO 9001:2015 www.cbsua.edu.ph
TÜV-R 01 100 1934918

30
23.3333
Same concept applies on function declaration where you provide a
function name at the time of its declaration and its actual definition can
be given anywhere else. For example −
// function declaration
int func();
int main() {
// function call
int i = func();
}

// function definition
int func() {
return 0;
}
Lvalues and Rvalues
There are two kinds of expressions in C++ −
 lvalue − Expressions that refer to a memory location is called
"lvalue" expression. An lvalue may appear as either the left-hand or
right-hand side of an assignment.
 rvalue − The term rvalue refers to a data value that is stored at
some address in memory. An rvalue is an expression that cannot
have a value assigned to it which means an rvalue may appear on
the right- but not left-hand side of an assignment.
Variables are lvalues and so may appear on the left-hand side of an
assignment. Numeric literals are rvalues and so may not be assigned and
can not appear on the left-hand side. Following is a valid statement −
int g = 20;
But the following is not a valid statement and would generate compile-
time error −
10 = 20;

There are some rules that must be in your knowledge to work with C++
variables.

Rules of Declaring variables in C++

 A variable name can consist of Capital letters A-Z, lowercase letters


a-z, digits 0-9, and the underscore character.
 The first character must be a letter or underscore.
Republic of the Philippines
CENTRAL BICOL STATE UNIVERSITY OF AGRICULTURE
San Jose, Pili, Camarines Sur 4418
ISO 9001:2015 www.cbsua.edu.ph
TÜV-R 01 100 1934918

 Blank spaces cannot be used in variable names.


 Special characters like #, $ are not allowed.
 C++ keywords cannot be used as variable names.
 Variable names are case-sensitive.
 A variable name can be consisting of 31 characters only if we
declare a variable more than one characters compiler will ignore
after 31 characters.
 Variable type can be bool, char, int, float, double, void or wchar_t.

Local Variables
Variables that are declared inside a function or block are local variables.
They can be used only by statements that are inside that function or
block of code. Local variables are not known to functions outside their
own. Following is the example using local variables −
#include <iostream>
using namespace std;

int main () {
// Local variable declaration:
int a, b;
int c;

// actual initialization
a = 10;
b = 20;
c = a + b;

cout << c;

return 0;
}

Global Variables
Global variables are defined outside of all the functions, usually on top of
the program. The global variables will hold their value throughout the life-
time of your program.
A global variable can be accessed by any function. That is, a global
variable is available for use throughout your entire program after its
declaration. Following is the example using global and local variables −
#include <iostream>
Republic of the Philippines
CENTRAL BICOL STATE UNIVERSITY OF AGRICULTURE
San Jose, Pili, Camarines Sur 4418
ISO 9001:2015 www.cbsua.edu.ph
TÜV-R 01 100 1934918

using namespace std;

// Global variable declaration:


int g;

int main () {
// Local variable declaration:
int a, b;

// actual initialization
a = 10;
b = 20;
g = a + b;

cout << g;

return 0;
}

A program can have same name for local and global variables but value
of local variable inside a function will take preference. For example −
#include <iostream>
using namespace std;

// Global variable declaration:


int g = 20;

int main () {
// Local variable declaration:
int g = 10;

cout << g;

return 0;
}
When the above code is compiled and executed, it produces the following
result −
10
Initializing Local and Global Variables
When a local variable is defined, it is not initialized by the system, you
must initialize it yourself. Global variables are initialized automatically by
the system when you define them as follows −

Data Type Initializer


Republic of the Philippines
CENTRAL BICOL STATE UNIVERSITY OF AGRICULTURE
San Jose, Pili, Camarines Sur 4418
ISO 9001:2015 www.cbsua.edu.ph
TÜV-R 01 100 1934918

int 0

char '\0'

float 0

double 0

pointer NULL

Learning Resources
6. CBSUA Website
7. Student Handbook
8. Fundamentals of Computing 1 (SY 2020-2021) Syllabus
9. Google.com
10. PowerPoint Presentation

Uploaded in this Google Drive Folder.

Tasks/Activities

• Lecture Discussion (Zoom/Google Meet) – Recorded


• PowerPoint Presentation
• Video Clips
• Quiz via google doc

Discussion Board

A Facebook group chat will be created where the students can discuss their ideas and thoughts. Chat
in Facebook Group allow us to communicate between users in a chat channel. Virtual Learning Portal
(VLP) will be the main source of lessons on the topic. This platform will be utilized throughout the
course.

Competency Checklist (Formative Assessment/Diagnostic)

The student will be assessed by filling out a questionnaire in google doc regarding the lessons that
have been presented. This assessment will determine the knowledge that they’ve learned with the
Video Lectures Presentation.
Instructions:

4. This is an individual activity.


Republic of the Philippines
CENTRAL BICOL STATE UNIVERSITY OF AGRICULTURE
San Jose, Pili, Camarines Sur 4418
ISO 9001:2015 www.cbsua.edu.ph
TÜV-R 01 100 1934918

5. Login to their institutional account


6. Check updated assessment

Tasks/Activities

• Answer the questionnaire


• Video presentation PowerPoint Presentation
• Video Clips

Week 6 to 8

Chapter 3 OVERLOADING (FUNCTION AND OPERATOR)

INTRODUCTION

C++ allows you to specify more than one definition for a function name
or an operator in the same scope, which is called function
overloading and operator overloading respectively.
An overloaded declaration is a declaration that is declared with the same
name as a previously declared declaration in the same scope, except that
both declarations have different arguments and obviously different
definition (implementation).
When you call an overloaded function or operator, the compiler
determines the most appropriate definition to use, by comparing the
argument types you have used to call the function or operator with the
parameter types specified in the definitions. The process of selecting the
most appropriate overloaded function or operator is called overload
resolution.
3.1 CONCEPT OF OVERLOADING
Overloading refers to the ability to use a single identifier to define multiple
methods of a class that differ in their input and output parameters.
Overloaded methods are generally used when they conceptually execute
the same task but with a slightly different set of parameters. Overloading
is a concept used to avoid redundant code where the same method name
is used multiple times but with a different set of parameters. The actual
method that gets called during runtime is resolved at compile time, thus
avoiding runtime errors. Overloading provides code clarity, eliminates
complexity, and enhances runtime performance. Overloading is used in
Republic of the Philippines
CENTRAL BICOL STATE UNIVERSITY OF AGRICULTURE
San Jose, Pili, Camarines Sur 4418
ISO 9001:2015 www.cbsua.edu.ph
TÜV-R 01 100 1934918

programming languages that enforce type-checking in function calls


during compilation. When a method is overloaded, the method chosen will
be selected at compile time. This is not the same as virtual functions
where the method is defined at runtime. Unlike Java, C# allows operators
to be overloaded, in addition to methods, by defining static members
using the operator keyword. This feature helps to extend and customize
the semantics of operators relevant to user-defined types so that they can
be used to manipulate object instances with operators. The overload
resolution in C# is the method by which the right function is selected on
the basis of arguments passed and the list of candidate function members
that have the same name.
The different contexts in which the overload resolution is used include:

 Invocation of a method in an expression


 Constructor during object creation
 Indexer access or through an element access and predefined or
user-defined operator expression

3.2 TYPE OF OVERLOADING


Overloading: When a single Object has multiple behaviors. Then it is
called as Overloading, Overloading is that in which a Single Object has a
same name and Provides Many Functions. In Overloading followings things
denotes Overloading:
 When an Object has Same Name.
 Difference is Return type.
 Difference in Function, with Multiple Arguments.
 Difference in Data Type.

3.2.1 Constructor Overloading


Constructor overloading is that in which a Constructor has a same name
and has multiple Functions, then it is called as Constructor Overloading.
As we know that Constructor are of Default, Parameterized and Copy
Constructors. So that when we are creating a Single Constructor with
Multiple Arguments then it is called as Constructor Overloading.
3.2.2 Operator Overloading
As we know that Operators are used for Performing Operations on the
Operands. But Each and Every Operator has Some Limitations Means an
Operator which is also called as Binary are used for Performing Operations
on the two Operands and Unary Operators performs their Operation on
the single Operand. So with the help of Operator Overloading, we can
change the Operation of the Operator. Means With the help of Operators
Republic of the Philippines
CENTRAL BICOL STATE UNIVERSITY OF AGRICULTURE
San Jose, Pili, Camarines Sur 4418
ISO 9001:2015 www.cbsua.edu.ph
TÜV-R 01 100 1934918

we can Change the Operation of the Operators. But With the help of
Operator Overloading we can Change the behavior of the unary Operator
means we can perform Operations means we can Increase or Decrease
the values of two or more Operands at a Time. And With the Help of
Comparison Operators we can also compare the Two Objects Means all
the Data Members of one Object can be compared with the Data Members
of the Other Object. Without the help of Operator Overloading this is not
possible to compare two Objects. So with the help of Comparison
Operators we can compare two Objects.

3.2.3 Method Overloading


Method Overloading is also called as Function Overloading. Overloading
Means a Functions has many Behaviors occurred When in class when a
functions has same name but different behaviors A Functions said to be
overloaded
When :-
 Function has same Name but Different Return Type
 Difference in No of Arguments
 Different Return Type in Arguments
When We Pass a Call for Execution then it will match the Criteria of
Function like Number of Arguments and Data types etc.

3.3 Function Overloading in C++

You can have multiple definitions for the same function name in the same
scope. The definition of the function must differ from each other by the
types and/or the number of arguments in the argument list. You cannot
overload function declarations that differ only by return type.
Following is the example where same function print() is being used to
print different data types −
#include <iostream>
using namespace std;

class printData {
public:
void print(int i) {
cout << "Printing int: " << i << endl;
}
void print(double f) {
cout << "Printing float: " << f << endl;
}
void print(char* c) {
cout << "Printing character: " << c << endl;
}
Republic of the Philippines
CENTRAL BICOL STATE UNIVERSITY OF AGRICULTURE
San Jose, Pili, Camarines Sur 4418
ISO 9001:2015 www.cbsua.edu.ph
TÜV-R 01 100 1934918

}
;
int main(void) {
printData pd;

// Call print to print integer


pd.print(5);

// Call print to print float


pd.print(500.263);

// Call print to print character


pd.print("Hello C++");

return 0;
}
When the above code is
compiled and executed, it
produces the following result

Printing int: 5
Printing float: 500.263
Printing character: Hello C++

Operators Overloading in C++

You can redefine or overload most of the built-in operators available in C+


+. Thus, a programmer can use operators with user-defined types as well.
Overloaded operators are functions with special names: the keyword
"operator" followed by the symbol for the operator being defined. Like
any other function, an overloaded operator has a return type and a
parameter list.
Box operator+(const Box&);
declares the addition operator that can be used to add two Box objects
and returns final Box object. Most overloaded operators may be defined
as ordinary non-member functions or as class member functions. In case
we define above function as non-member function of a class then we
would have to pass two arguments for each operand as follows −
Box operator+(const Box&, const Box&);
Following is the example to show the concept of operator over loading
using a member function. Here an object is passed as an argument whose
Republic of the Philippines
CENTRAL BICOL STATE UNIVERSITY OF AGRICULTURE
San Jose, Pili, Camarines Sur 4418
ISO 9001:2015 www.cbsua.edu.ph
TÜV-R 01 100 1934918

properties will be accessed using this object, the object which will call this
operator can be accessed using this operator as explained below −
#include <iostream>
using namespace std;

class Box {
public:
double getVolume(void) {
return length * breadth * height;
}
void setLength( double len ) {
length = len;
}
void setBreadth( double bre ) {
breadth = bre;
}
void setHeight( double hei ) {
height = hei;
}

// Overload + operator to add two Box objects.


Box operator+(const Box& b) {
Box box;
box.length = this->length + b.length;
box.breadth = this->breadth + b.breadth;
box.height = this->height + b.height;
return box;
}

private:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
};

// Main function for the program


int main() {
Box Box1; // Declare Box1 of type Box
Box Box2; // Declare Box2 of type Box
Box Box3; // Declare Box3 of type Box
double volume = 0.0; // Store the volume of a box here

// box 1 specification
Box1.setLength(6.0);
Box1.setBreadth(7.0);
Box1.setHeight(5.0);
Republic of the Philippines
CENTRAL BICOL STATE UNIVERSITY OF AGRICULTURE
San Jose, Pili, Camarines Sur 4418
ISO 9001:2015 www.cbsua.edu.ph
TÜV-R 01 100 1934918

// box 2 specification
Box2.setLength(12.0);
Box2.setBreadth(13.0);
Box2.setHeight(10.0);

// volume of box 1
volume = Box1.getVolume();
cout << "Volume of Box1 : " << volume <<endl;

// volume of box 2
volume = Box2.getVolume();
cout << "Volume of Box2 : " << volume <<endl;

// Add two object as follows:


Box3 = Box1 + Box2;

// volume of box 3
volume = Box3.getVolume();
cout << "Volume of Box3 : " << volume <<endl;

return 0;
}

When the above code is compiled and executed, it produces the following
result −
Volume of Box1 : 210
Volume of Box2 : 1560
Volume of Box3 : 5400

Overloadable/Non-overloadable Operators

Following is the list of operators which can be overloaded −

+ - * / % ^

& | ~ ! , =
Republic of the Philippines
CENTRAL BICOL STATE UNIVERSITY OF AGRICULTURE
San Jose, Pili, Camarines Sur 4418
ISO 9001:2015 www.cbsua.edu.ph
TÜV-R 01 100 1934918

< > <= >= ++ --

<< >> == != && ||

+= -= /= %= ^= &=

|= *= <<= >>= [] ()

-> ->* new new [] delete delete []

 Following is the list of operators, which cannot be overloaded −

:: .* . ?:

Learning Resources
11. CBSUA Website
12. Student Handbook
13. Fundamentals of Computing 1 (SY 2020-2021) Syllabus
14. Google.com
15. PowerPoint Presentation

Uploaded in this Google Drive Folder.

Tasks/Activities

• Lecture Discussion (Zoom/Google Meet) – Recorded


• PowerPoint Presentation
• Video Clips
• Quiz via google doc

Discussion Board

A Facebook group chat will be created where the students can discuss their ideas and thoughts. Chat
in Facebook Group allow us to communicate between users in a chat channel. Virtual Learning Portal
(VLP) will be the main source of lessons on the topic. This platform will be utilized throughout the
course.

Competency Checklist (Formative Assessment/Diagnostic)


Republic of the Philippines
CENTRAL BICOL STATE UNIVERSITY OF AGRICULTURE
San Jose, Pili, Camarines Sur 4418
ISO 9001:2015 www.cbsua.edu.ph
TÜV-R 01 100 1934918

The student will be assessed by filling out a questionnaire in google doc regarding the lessons that
have been presented. This assessment will determine the knowledge that they’ve learned with the
Video Lectures Presentation.
Instructions:

7. This is an individual activity.


8. Login to their institutional account
9. Check updated assessment

Tasks/Activities

• Answer the questionnaire


• Video presentation PowerPoint Presentation
• Video Clips

Week 9 – 11
Chapter 4 INHERITANCE

Introduction
One of the most important concepts in object-oriented programming is
that of inheritance. Inheritance allows us to define a class in terms of
another class, which makes it easier to create and maintain an
application. This also provides an opportunity to reuse the code
functionality and fast implementation time. When creating a class, instead
of writing completely new data members and member functions, the
programmer can designate that the new class should inherit the members
of an existing class. This existing class is called the base class, and the
new class is referred to as the derived class. The idea of inheritance
implements the is a relationship. For example, mammal IS-A animal, dog
IS-A mammal hence dog IS-A animal as well and so on. Inheritance is one
of the core features of an object- oriented programming language. It
allows software developers to derive a new class from the existing class.
The derived class inherits the features of the base class (existing class).
The technique of deriving a new class from an old one is called
inheritance. The old class is referred to as base class and the new class is
referred to as derived class or subclass. Inheritance concept allows
programmers to define a class in terms of another class, which makes
creating and maintaining application easier. When writing a new class,
instead of writing new data member and member functions all over again,
programmers can make a bonding of the new class with the old one that
the new class should inherit the members of the existing class. A class can
get derived from one or more classes, which means it can inherit data and
functions from multiple base classes.
Republic of the Philippines
CENTRAL BICOL STATE UNIVERSITY OF AGRICULTURE
San Jose, Pili, Camarines Sur 4418
ISO 9001:2015 www.cbsua.edu.ph
TÜV-R 01 100 1934918

4.1 CONCEPT OF INHERITANCE


A class can inherit from zero or more base classes. A class with at least
one base class is said to be a derived class. A derived class inherits all the
data members and member functions of all of its base classes and all of
their base classes, and so on. A class's immediate base classes are called
direct base classes. Their base classes are indirect base classes. The
complete set of direct and indirect base classes is sometimes called the
ancestor classes. A class can derive directly from any number of base
classes. The base-class names follow a colon and are separated by
commas. Each class name can be prefaced by an access specifier. The
same class cannot be listed more than once as direct base class, but it
can appear more than once in the inheritance graph.

Base and Derived Classes


A class can be derived from more than one classes, which means it can
inherit data and functions from multiple base classes. To define a derived
class, we use a class derivation list to specify the base class(es). A class
derivation list names one or more base classes and has the form −
class derived-class: access-specifier base-class
Where access-specifier is one of public, protected, or private, and
base-class is the name of a previously defined class. If the access-
specifier is not used, then it is private by default.
Consider a base class Shape and its derived class Rectangle as follows

#include <iostream>

using namespace std;

// Base class
class Shape {
public:
void setWidth(int w) {
width = w;
}
void setHeight(int h) {
height = h;
}
protected:
int width;
int height;
Republic of the Philippines
CENTRAL BICOL STATE UNIVERSITY OF AGRICULTURE
San Jose, Pili, Camarines Sur 4418
ISO 9001:2015 www.cbsua.edu.ph
TÜV-R 01 100 1934918

};

// Derived class
class Rectangle: public Shape {
public:
int getArea() {
return (width * height);
}
};

int main(void) {
Rectangle Rect;

Rect.setWidth(5);
Rect.setHeight(7);

// Print the area of the object.


cout << "Total area: " << Rect.getArea() << endl;

return 0;
}
When the above code is compiled and executed, it produces the following
result −
Total area: 35

Access Control and Inheritance

A derived class can access all the non-private members of its base class.
Thus base-class members that should not be accessible to the member
functions of derived classes should be declared private in the base class.
We can summarize the different access types according to - who can
access them in the following way −

Access public protected private

Same class yes yes yes

Derived classes yes yes no

Outside classes yes no no


Republic of the Philippines
CENTRAL BICOL STATE UNIVERSITY OF AGRICULTURE
San Jose, Pili, Camarines Sur 4418
ISO 9001:2015 www.cbsua.edu.ph
TÜV-R 01 100 1934918

A derived class inherits all base class methods with the following
exceptions −

 Constructors, destructors and copy constructors of the base class.


 Overloaded operators of the base class.
 The friend functions of the base class.

Type of Inheritance

When deriving a class from a base class, the base class may be inherited
through public, protected or private inheritance. The type of
inheritance is specified by the access-specifier as explained above.
We hardly use protected or private inheritance, but public inheritance
is commonly used. While using different type of inheritance, following
rules are applied −
 Public Inheritance − When deriving a class from a public base
class, public members of the base class become public members
of the derived class and protected members of the base class
become protected members of the derived class. A base
class's private members are never accessible directly from a
derived class, but can be accessed through calls to
the public and protected members of the base class.
 Protected Inheritance − When deriving from a protected base
class, public and protected members of the base class
become protected members of the derived class.
 Private Inheritance − When deriving from a private base
class, public and protected members of the base class
become private members of the derived class.

4.2 Multiple Inheritance

A C++ class can inherit members from more than one class and here is
the extended syntax −
class derived-class: access baseA, access baseB....
Where access is one of public, protected, or private and would be
given for every base class and they will be separated by comma as
shown above. Let us try the following example −
#include <iostream>

using namespace std;

// Base class Shape


class Shape {
Republic of the Philippines
CENTRAL BICOL STATE UNIVERSITY OF AGRICULTURE
San Jose, Pili, Camarines Sur 4418
ISO 9001:2015 www.cbsua.edu.ph
TÜV-R 01 100 1934918

public:
void setWidth(int w) {
width = w;
}
void setHeight(int h) {
height = h;
}

protected:
int width;
int height;
};

// Base class PaintCost


class PaintCost {
public:
int getCost(int area) {
return area * 70;
}
};

// Derived class
class Rectangle: public Shape, public PaintCost {
public:
int getArea() {
return (width * height);
}
};

int main(void) {
Rectangle Rect;
int area;

Rect.setWidth(5);
Rect.setHeight(7);

area = Rect.getArea();

// Print the area of the object.


cout << "Total area: " << Rect.getArea() << endl;

// Print the total cost of painting


cout << "Total paint cost: $" << Rect.getCost(area) << endl;

return 0;
}
Republic of the Philippines
CENTRAL BICOL STATE UNIVERSITY OF AGRICULTURE
San Jose, Pili, Camarines Sur 4418
ISO 9001:2015 www.cbsua.edu.ph
TÜV-R 01 100 1934918

When the above code is compiled and executed, it produces the following
result −
Total area: 35
Total paint cost: $2450

The derived class inherits the features from the base class and can
have additional features of its own. For example,

class Animal {
// eat() function
// sleep() function
};

class Dog : public Animal {


// bark() function
};

Here, the Dog class is derived from the Animal class. Since Dog is derived
from Animal, members of Animal are accessible to Dog.

Inheritance in C++
Notice the use of the keyword public while inheriting Dog from Animal.
Republic of the Philippines
CENTRAL BICOL STATE UNIVERSITY OF AGRICULTURE
San Jose, Pili, Camarines Sur 4418
ISO 9001:2015 www.cbsua.edu.ph
TÜV-R 01 100 1934918

class Dog : public Animal {...};

We can also use the keywords private and protected instead of public.
We will learn about the differences between
using private, public and protected later in this tutorial.

is-a relationship

Inheritance is an is-a relationship. We use inheritance only if an is-a


relationship is present between the two classes.
Here are some examples:

 A car is a vehicle.

 Orange is a fruit.

 A surgeon is a doctor.

 A dog is an animal.

Example 1: Simple Example of C++ Inheritance

// C++ program to demonstrate inheritance

#include <iostream>
using namespace std;

// base class
class Animal {

public:
void eat() {
cout << "I can eat!" << endl;
}

void sleep() {
cout << "I can sleep!" << endl;
}
};
Republic of the Philippines
CENTRAL BICOL STATE UNIVERSITY OF AGRICULTURE
San Jose, Pili, Camarines Sur 4418
ISO 9001:2015 www.cbsua.edu.ph
TÜV-R 01 100 1934918

// derived class
class Dog : public Animal {

public:
void bark() {
cout << "I can bark! Woof woof!!" << endl;
}
};

int main() {
// Create object of the Dog class
Dog dog1;

// Calling members of the base class


dog1.eat();
dog1.sleep();

// Calling member of the derived class


dog1.bark();

return 0;
}

Output

I can eat!
I can sleep!
I can bark! Woof woof!!

Here, dog1 (the object of derived class Dog) can access members of the
base class Animal. It's because Dog is inherited from Animal.

// Calling members of the Animal class


dog1.eat();
dog1.sleep();

You might also like