OOP C++
OOP C++
****** ******
Paix-Travail-Patrie Peace-Work-Fatherland
****** ******
NISTERE DE L’ENSEIGNEMENT SUPERIEUR MINISTRY OF HIGHER EDUCATION
****** ******
UT SUPERIEUR DES SCIENCES DE L’INDUSTRIE HIGHER INSTITUTE OF INDUSTRIAL SCIENCES
4Th SEMESTER
CHAPTER ONE : CONCEPT ON OBJECT ORIENTED
PROGRAMMING (OOP)
What is Object-Oriented Programming?
Object-oriented programming has a sweeping impact because it appeals at multiple levels
and promises faster and cheaper development and maintenance. It follows a bottom-up
approach to develop applications.
Object-Oriented Programming
The word object-oriented is the combination of two words i.e. object and oriented. The
dictionary meaning of the object is an article or entity that exists in the real world. The
meaning of oriented is interested in a particular kind of thing or entity. In layman's terms, it is
a programming pattern that rounds around an object or entity are called object-oriented
programming.
An object is referred to as a data field that has unique attributes and behavior. Everything in
OOP is grouped as self-sustainable objects.
It is the most popular programming model among developers. It is well suited for programs
that are large, complex, and actively updated or maintained. It simplifies software
development and maintenance by providing major concepts such as abstraction,
inheritance, polymorphism, and encapsulation. These core concepts support OOP.
A real-world example of OOP is the automobile. It more completely illustrates the power of
object-oriented design.
Points to Remember
o Everything is an object
o Developer manipulates objects that uses message passing.
o Every object is an instance of a class.
o The class contains the attribute and behavior associated with an object.
Pillars of OOPs
The major concepts that we have discussed above are known as pillars of OOPs. There
are four pillars on which OOP rests.
o Abstraction
o Encapsulation
o Inheritance
o Polymorphism
Abstraction
The concept allows us to hide the implementation from the user but shows only essential
information to the user. Using the concept developer can easily make changes and added over
time.
There are the following advantages of abstraction:
o It reduces complexity.
o It avoids delicacy.
o Eases the burden of maintenance
o Increase security and confidentially.
Encapsulation
Encapsulation is a mechanism that allows us to bind data and functions of a class into an
entity. It protects data and functions from outside interference and misuse. Therefore, it also
provides security. A class is the best example of encapsulation.
Inheritance
The concept allows us to inherit or acquire the properties of an existing class (parent class)
into a newly created class (child class). It is known as inheritance. It provides code
reusability.
Polymorphism
The word polymorphism is derived from the two words i.e. ploy and morphs. Poly means
many and morphs means forms. It allows us to create methods with the same name but
different method signatures. It allows the developer to create clean, sensible, readable, and
resilient code.
The above figure best describes the concepts of polymorphism. A person plays an employee
role in the office, father and husband role in the home.
OOPs Concepts
1. Object
2. Class
3. Inheritance
4. Polymorphism
5. Abstraction
6. Encapsulation
Object
An object is a real-world entity that has attributes, behavior, and properties. It is referred to as
an instance of the class. It contains member functions, variables that we have defined in the
class. It occupies space in the memory. Different objects have different states or attributes,
and behaviors.
Class
A class is a blueprint or template of an object. It is a user-defined data type. Inside a class, we
define variables, constants, member functions, and other functionality. it binds data and
functions together in a single unit. It does not consume memory at run time. Note that classes
are not considered as a data structure. It is a logical entity. It is the best example of data
binding. Note that a class can exist without an object but vice-versa is not possible.
The following figure best illustrates the class and object in OOP.
Apart from these core concepts, there are some other object-oriented concepts used in OOP.
Coupling
In programming, separation of concerns is known as coupling. It means that an object cannot
directly change or modify the state or behavior of other objects. It defines how closely two
objects are connected together. There are two types of coupling, loose coupling,
and tight coupling.
Objects that are independent of one another and do not directly modify the state of other
objects is called loosely coupled. Loose coupling makes the code more flexible, changeable,
and easier to work with.
Objects that depend on other objects and can modify the states of other objects are called
tightly coupled. It creates conditions where modifying the code of one object also requires
changing the code of other objects. The reuse of code is difficult in tight coupling because we
cannot separate the code.
Cohesion
In OOP, cohesion refers to the degree to which the elements inside a module belong together.
It measures the strength of the relationship between the module and data. In short, cohesion
represents the clarity of the responsibilities of a module. It is often contrasted with coupling.
It focuses on a how single module or class is intended. Higher the cohesiveness of the module
or class, better is the object-oriented design.
There are two types of cohesion, i.e. High and Low.
High cohesion often associates with loose coupling and vice versa.
Composition
Composition is one of the vital concepts in OOP. It describes a class that references one or
more objects of other classes in instance variables. It allows us to model a has-a association
between objects. We can find such relationships in the real world. For example, a car has an
engine. the following figure depicts the same
The main benefits of composition are:
Association
The association defines the relationship between the objects. Note that an object can be
associated with one or more than one object. The relationship can be unidirectional or
bidirectional. There are the following types of association.
o One to One
o One to Many
o Many to One, and
o Many to Many
Aggregation
It is an advanced form of association in which each object has its own Lifecycle but there
exists ownership as well. In other words, a relationship where a child can exist independently
of the parent. It is also termed as has-a relationship in Java. Like, inheritance represents the
is-a relationship. It is another way to reuse objects.
OOP is often the best use when we are dealing with manufacturing and designing
applications. It provides modularity in programming. It allows us to break down the software
into chunks of small problems that we then can solve one object at a time.
It should be used where the reusability of code and maintenance is a major concern. Because
it makes development easy and we can easily append code without affecting other code
blocks. It should be used where complex programming is a challenge.
Benefits of OOP
Limitations of OOP
There are various object-oriented programming languages are present. But we have enlisted
some popular and widely used OOP languages.
Applications of OOPs
INTRO TO C++
C++ tutorial provides basic and advanced concepts of C++. Our C++ tutorial is designed for
beginners and professionals.
Our C++ tutorial includes all topics of C++ such as first example, control statements,
objects and classes, inheritance, constructor, destructor, this, static, polymorphism,
abstraction, abstract class, interface, namespace, encapsulation, arrays, strings, exception
handling, File IO, etc.
What is C++
C++ supports the object-oriented programming, the four major pillar of object-oriented
programming used in C++ are:
1. Inheritance
2. Polymorphism
3. Encapsulation
4. Abstraction
o The core library includes the data types, variables and literals, etc.
o The standard library includes the set of functions manipulating strings, files, etc.
o The Standard Template Library (STL) includes the set of methods manipulating a
data structure.
Usage of C++
By the help of C++ programming language, we can develop different types of secured and
robust applications:
o Window application
o Client-Server application
o Device drivers
o Embedded firmware etc
C++ Program
In this tutorial, all C++ programs are given with C++ compiler so that you can easily
change the C++ program code.
File: main.cpp
1. #include <iostream> //
2. using namespace std;
3. int main() {
4. cout << "Hello C++ Programming";
5. return 0;
6. }
A detailed explanation of first C++ program is given in next chapters.
No. C C++ C vs C++
7) In C, scanf() and printf() are C++ mainly uses stream cin and
mainly used for input/output. cout to perform input and output
operations.
10) C does not provide the feature of C++ supports the feature of
namespace. namespace.
11) Exception handling is not easy in C. C++ provides exception handling
It has to perform using other using Try and Catch block.
functions.
C++ history
History of C++ language is interesting to know. Here we are going to discuss brief history
of C++ language.
History of C++ language is interesting to know. Here we are going to discuss brief history of C++ langua
C++ programming language was developed in 1980 by Bjarne Stroustrup at bell laboratories of AT&T (
Telegraph), located in U.S.A.
It was develop for adding a feature of OOP (Object Oriented Programming) in C without significantly c
component.
C++ programming is "relative" (called a superset) of C, it means any valid C program is also a valid C++ p
Let's see the programming languages that were developed before C++ language.
Before starting the abcd of C++ language, you need to learn how to write, compile and run
the first C++ program.
To write the first C++ program, open the C++ console and write the following code:
1. #include <iostream.h>
2. #include<conio.h>
3. void main() {
4. clrscr();
5. cout << "Welcome to C++ Programming.";
6. getch();
7. }
#include <conio.h> includes the console input output library functions. The getch()
function is defined in conio.h file.
void main() The main() function is the entry point of every program in C++ language.
The void keyword specifies that it returns no value.
cout << "Welcome to C++ Programming." is used to print the data "Welcome to C++
Programming." on the console.
getch() The getch() function asks for a single character. Until you press any key, it blocks
the screen.
How to compile and run the C++ program
There are 2 ways to compile and run the C++ program, by menu and by shortcut.
By menu
Now click on the compile menu then compile sub menu to compile the c++ program.
Then click on the run menu then run sub menu to run the c++ program.
By shortcut
Or, press ctrl+f9 keys compile and run the program directly.
C++ I/O operation is using the stream concept. Stream is the sequence of bytes or flow of
data. It makes the performance fast.
If bytes flow from main memory to device like printer, display screen, or a network
connection, etc, this is called as output operation.
If bytes flow from device like printer, display screen, or a network connection, etc to main
memory, this is called as input operation.
Let us see the common header files used in C++ programming are:
<iostream> It is used to define the cout, cin and cerr objects, which correspond
to standard output stream, standard input stream and standard error
stream, respectively.
1. #include <iostream>
2. using namespace std;
3. int main( ) {
4. char ary[] = "Welcome to C++ tutorial";
5. cout << "Value of ary is: " << ary << endl;
cout<< ―HELLO HWM INSAM‖;
//in c programming – printf(―hello world \n‖);
6. }
Output:
The cin is a predefined object of istream class. It is connected with the standard input device,
which is usually a keyboard. The cin is used in conjunction with stream extraction operator
(>>) to read the input from a console.
1. #include <iostream>
2. using namespace std;
3. int main( ) {
4. int age;
5. cout << "Enter your age: ";
6. cin >> age;
7. cout << "Your age is: " << age << endl;
8. }
Output:
The endl is a predefined object of ostream class. It is used to insert a new line characters and
flushes the stream.
Let's see the simple example of standard end line (endl):
1. #include <iostream>
2. using namespace std;
3. int main( ) {
4. cout << "C++ Tutorial";
5. cout << " Javatpoint"<<endl;
6. cout << "End of line"<<endl; // ―\n‖
7. }
Output:
C++ Variable
A variable is a name of memory location. It is used to store data. Its value can be changed
and it can be reused many times.
30 40
X Y
FFAB FFAC
It is a way to represent memory location through symbol so that it can be easily identified.
1. type variable_list;
1. int x;
2. float y;
3. char z;
Here, x, y, z are variables and int, float, char are data types.
We can also provide values while declaring the variables as given below:
1. int a;
2. int _ab;
3. int a30;
4. float f;
1. int 4;
2. int x y;
3. int double;
4. int int;
C++ Data Types
A data type specifies the type of data that a variable can store such as integer, floating,
character etc.
The basic data types are integer-based and floating-point based. C++ language supports both
signed and unsigned literals.
The memory size of basic data types may change according to 32-Z or 64-bit operating
system.
Let's see the basic data types. It size is given according to 32 bit OS.
Float 4 byte
Double 8 byte
C++ Keywords
A keyword is a reserved word. You cannot use it as a variable name, constant name etc. A
list of 32 Keywords in C++ Language which are also available in C language are given
below.
A list of 30 Keywords in C++ Language which are not available in C language are given
below.
C++ Operators
An operator is simply a symbol that is used to perform operations. There can be many types
of operations like arithmetic, logical, bitwise etc.
There are following types of operators to perform different types of operations in C language.
o Arithmetic Operators
o Relational Operators
o Logical Operators
o Bitwise Operators
o Assignment Operator
o Unary operator
o Ternary or Conditional Operator
o Misc Operator
Precedence of Operators in C++
The precedence of operator species that which operator will be evaluated first and next. The
associativity specifies the operators direction to be evaluated, it may be left to right or right to
left.
1. int data=5+10*10;
The "data" variable will contain 105 because * (multiplicative operator) is evaluated before +
(additive operator).
#include <iostream>
using namespace std;
int main(){
int num1 = 240;
int num2 = 40;
cout<<"num1 + num2: "<<(num1 + num2)<<endl;
cout<<"num1 - num2: "<<(num1 - num2)<<endl;
cout<<"num1 * num2: "<<(num1 * num2)<<endl;
cout<<"num1 / num2: "<<(num1 / num2)<<endl;
cout<<"num1 % num2: "<<(num1 % num2)<<endl;
return 0;
}
Output:
#include <iostream>
using namespace std;
int main(){
int num1 = 240;
int num2 = 40;
num2 = num1;
cout<<"= Output: "<<num2<<endl;
num2 += num1;
cout<<"+= Output: "<<num2<<endl;
num2 -= num1;
cout<<"-= Output: "<<num2<<endl;
num2 *= num1;
cout<<"*= Output: "<<num2<<endl;
num2 /= num1;
cout<<"/= Output: "<<num2<<endl;
num2 %= num1;
cout<<"%= Output: "<<num2<<endl;
return 0;
}
Output:
= Output: 240
+= Output: 480
-= Output: 240
*= Output: 57600
/= Output: 240
%= Output: 0
3) Auto-increment and Auto-decrement Operators
++ and —
num++ is equivalent to num=num+1;
num–- is equivalent to num=num-1;
#include <iostream>
using namespace std;
int main(){
int num1 = 240;
int num2 = 40;
num1++; num2--;
cout<<"num1++ is: "<<num1<<endl;
cout<<"num2-- is: "<<num2;
return 0;
}
Output:
Logical Operators are used with binary variables. They are mainly used in conditional
statements and loops for evaluating a condition.
b1&&b2 will return true if both b1 and b2 are true else it would return false.
b1||b2 will return false if both b1 and b2 are false else it would return true.
!b1 would return the opposite of b1, that means it would be true if b1 is false and it would
return false if b1 is true.
#include <iostream>
using namespace std;
int main(){
bool b1 = true;
bool b2 = false;
cout<<"b1 && b2: "<<(b1&&b2)<<endl;
cout<<"b1 || b2: "<<(b1||b2)<<endl;
cout<<"!(b1 && b2): "<<!(b1&&b2);
return 0;
}
Output:
b1 && b2: 0
b1 || b2: 1
!(b1 && b2): 1
5) Relational operators
We have six relational operators in C++: ==, !=, >, <, >=, <=
== returns true if both the left side and right side are equal
!= returns true if left side is not equal to the right side of operator.
>= returns true if left side is greater than or equal to right side.
<= returns true if left side is less than or equal to right side.
#include <iostream>
using namespace std;
int main(){
int num1 = 240;
int num2 =40;
if (num1==num2) {
cout<<"num1 and num2 are equal"<<endl;
}
else{
cout<<"num1 and num2 are not equal"<<endl;
}
if( num1 != num2 ){
cout<<"num1 and num2 are not equal"<<endl;
}
else{
cout<<"num1 and num2 are equal"<<endl;
}
if( num1 > num2 ){
cout<<"num1 is greater than num2"<<endl;
}
else{
cout<<"num1 is not greater than num2"<<endl;
}
if( num1 >= num2 ){
cout<<"num1 is greater than or equal to num2"<<endl;
}
else{
cout<<"num1 is less than num2"<<endl;
}
if( num1 < num2 ){
cout<<"num1 is less than num2"<<endl;
}
else{
cout<<"num1 is not less than num2"<<endl;
}
if( num1 <= num2){
cout<<"num1 is less than or equal to num2"<<endl;
}
else{
cout<<"num1 is greater than num2"<<endl;
}
return 0;
}
Output:
num1 | num2 compares corresponding bits of num1 and num2 and generates 1 if either bit is
1, else it returns 0. In our case it would return 31 which is 00011111
num1 ^ num2 compares corresponding bits of num1 and num2 and generates 1 if they are
not equal, else it returns 0. In our example it would return 29 which is equivalent to
00011101
~num1 is a complement operator that just changes the bit from 0 to 1 and 1 to 0. In our
example it would return -12 which is signed 8 bit equivalent to 11110100
num1 << 2 is left shift operator that moves the bits to the left, discards the far left bit, and
assigns the rightmost bit a value of 0. In our case output is 44 which is equivalent to
00101100
Note: In the example below we are providing 2 at the right side of this shift operator that is
the reason bits are moving two places to the left side. We can change this number and bits
would be moved by the number of bits specified on the right side of the operator. Same
applies to the right side operator.
num1 >> 2 is right shift operator that moves the bits to the right, discards the far right bit,
and assigns the leftmost bit a value of 0. In our case output is 2 which is equivalent to
00000010
#include <iostream>
using namespace std;
int main(){
int num1 = 11; /* 11 = 00001011 */
int num2 = 22; /* 22 = 00010110 */
int result = 0;
result = num1 & num2;
cout<<"num1 & num2: "<<result<<endl;
result = num1 | num2;
cout<<"num1 | num2: "<<result<<endl;
result = num1 ^ num2;
cout<<"num1 ^ num2: "<<result<<endl;
result = ~num1;
cout<<"~num1: "<<result<<endl;
result = num1 << 2;
cout<<"num1 << 2: "<<result<<endl;
result = num1 >> 2;
cout<<"num1 >> 2: "<<result;
return 0;
}
Output:
This operator evaluates a boolean expression and assign the value based on the result.
Syntax:
#include <iostream>
using namespace std;
int main(){
int num1, num2; num1 = 99;
/* num1 is not equal to 10 that's why
* the second value after colon is assigned
* to the variable num2
*/
num2 = (num1 == 10) ? 100: 200;
cout<<"num2: "<<num2<<endl;
/* num1 is equal to 99 that's why
* the first value is assigned
* to the variable num2
*/
num2 = (num1 == 99) ? 100: 200;
cout<<"num2: "<<num2;
return 0;
}
Output:
num2: 200
num2: 100
C++ Pointers
C++ pointers are easy and fun to learn. Some C++ tasks are performed more easily with
pointers, and other C++ tasks, such as dynamic memory allocation, cannot be performed
without them.
As you know every variable is a memory location and every memory location has its address
defined which can be accessed using ampersand (&) operator which denotes an address in
memory. Consider the following which will print the address of the variables defined −
#include <iostream>
int main () {
int var1;
char var2[10];
return 0;
When the above code is compiled and executed, it produces the following result −
A pointer is a variable whose value is the address of another variable. Like any variable or
constant, you must declare a pointer before you can work with it. The general form of a
pointer variable declaration is –
A B(POINTER)
20 FF01
FF01 FF02
type *var-name;
Here, type is the pointer's base type; it must be a valid C++ type and var-name is the name
of the pointer variable. The asterisk you used to declare a pointer is the same asterisk that
you use for multiplication. However, in this statement the asterisk is being used to designate
a variable as a pointer. Following are the valid pointer declaration −
The actual data type of the value of all pointers, whether integer, float, character, or
otherwise, is the same, a long hexadecimal number that represents a memory address. The
only difference between pointers of different data types is the data type of the variable or
constant that the pointer points to.
There are few important operations, which we will do with the pointers very
frequently. (a) We define a pointer variable. (b) Assign the address of a variable to a
pointer. (c) Finally access the value at the address available in the pointer variable. This is
done by using unary operator * that returns the value of the variable located at the address
specified by its operand. Following example makes use of these operations −
#include <iostream>
int main () {
return 0;
When the above code is compiled and executed, it produces result something as follows −
Pointers in C++
Pointers have many but easy concepts and they are very important to C++ programming.
There are following few important pointer concepts which should be clear to a C++
programmer −
1 Null Pointers
C++ supports null pointer, which is a constant with a value of zero defined in
several standard libraries.
2 Pointer Arithmetic
There are four arithmetic operators that can be used on pointers: ++, --, +, -
3 Pointers vs Arrays
4 Array of Pointers
5 Pointer to Pointer
C++ allows a function to return a pointer to local variable, static variable and
dynamically allocated memory as well.
A variable that is a pointer to a pointer must be declared as such. This is done by placing an
additional asterisk in front of its name. For example, following is the declaration to declare a
pointer to a pointer of type int −
int **var;
When a target value is indirectly pointed to by a pointer to a pointer, accessing that value
requires that the asterisk operator be applied twice, as is shown below in the example −
#include <iostream>
int main () {
int var;
int *ptr;
int **pptr;
var = 3000;
ptr = &var;
pptr = &ptr;
cout << "Value available at *ptr :" << *ptr << endl;
cout << "Value available at **pptr :" << **pptr << endl;
return 0;
When the above code is compiled and executed, it produces the following result −
As you understood pointer is an address which is a numeric value; therefore, you can
perform arithmetic operations on a pointer just as you can a numeric value. There are four
arithmetic operators that can be used on pointers: ++, --, +, and -
To understand pointer arithmetic, let us consider that ptr is an integer pointer which points to
the address 1000. Assuming 32-bit integers, let us perform the following arithmetic
operation on the pointer −
ptr++
the ptr will point to the location 1004 because each time ptr is incremented, it will point to
the next integer. This operation will move the pointer to next memory location without
impacting actual value at the memory location. If ptr points to a character whose address is
1000, then above operation will point to the location 1001 because next character will be
available at 1001.
Incrementing a Pointer
We prefer using a pointer in our program instead of an array because the variable pointer can
be incremented, unlike the array name which cannot be incremented because it is a constant
pointer. The following program increments the variable pointer to access each succeeding
element of the array −
#include <iostream>
using namespace std;
int main () {
int *ptr;
ptr = var;
ptr++;
return 0;
}
When the above code is compiled and executed, it produces result something as follows −
Decrementing a Pointer
The same considerations apply to decrementing a pointer, which decreases its value by the
number of bytes of its data type as shown below −
#include <iostream>
int main () {
int *ptr;
ptr = &var[MAX-1];
ptr--;
return 0;
When the above code is compiled and executed, it produces result something as follows −
Pointer Comparisons
Pointers may be compared by using relational operators, such as ==, <, and >. If p1 and p2
point to variables that are related to each other, such as elements of the same array, then p1
and p2 can be meaningfully compared.
The following program modifies the previous example one by incrementing the variable
pointer so long as the address to which it points is either less than or equal to the address of
the last element of the array, which is &var[MAX - 1] −
#include <iostream>
int main () {
int *ptr;
ptr = var;
int i = 0;
ptr++;
i++;
return 0;
}
When the above code is compiled and executed, it produces result something as follows −
C++ Functions
To perform any task, we can create function. A function can be called many times. It
provides modularity and code reusability.
Advantage of functions in C
1) Code Reusability
By creating functions in C++, you can call it many times. So we don't need to write the same
code again and again.
2) Code optimization
Suppose, you have to check 3 numbers (531, 883 and 781) whether it is prime number or not.
Without using function, you need to write the prime number logic 3 times. So, there is
repetition of code.
But if you use functions, you need to write the logic only once and you can reuse it several
times.
Types of Functions
1. Library Functions: are the functions which are declared in the C++ header files such as
ceil(x), cos(x), exp(x), etc.
2. User-defined functions: are the functions which are created by the C++ programmer, so
that he/she can use it many times. It reduces complexity of a big program and optimizes the
code.
Declaration of a function
Function without return type and with arguments (void add (int a, int b ))
1. #include <iostream>
2. using namespace std;
3. void func() {
4. static int i=0; //static variable
5. int j=0; //local variable
6. i++;
7. j++;
8. cout<<"i=" << i<<" and j=" <<j<<endl;
9. }
10. int main()
11. {
12. func();
13. func();
14. func();
15. }
Output:
i= 1 and j= 1
i= 2 and j= 1
i= 3 and j= 1
Call by value and call by reference in C++
There are two ways to pass value or data to function in C language: call by value and call by
reference. Original value is not modified in call by value but it is modified in call by
reference.
Let's understand call by value and call by reference in C++ language one by one.
In call by value, value being passed to the function is locally stored by the function parameter
in stack memory location. If you change the value of function parameter, it is changed for the
current function only. It will not change the value of variable inside the caller method such as
main().
Let's try to understand the concept of call by value in C++ language by the example given
below:
1. #include <iostream>
2. using namespace std;
3. void change(int data);
4. int main()
5. {
6. int data = 3;
7. change(data);
8. cout << "Value of the data is: " << data<< endl;
9. return 0;
10. }
11. void change(int data)
12. {
13. data = 5;
14. }
Output:
Here, address of the value is passed in the function, so actual and formal arguments share the
same address space. Hence, value changed inside the function, is reflected inside as well as
outside the function.
Note: To understand the call by reference, you must have the basic knowledge of pointers.
Let's try to understand the concept of call by reference in C++ language by the example given
below:
1. #include<iostream>
2. using namespace std;
3. void swap(int *x, int *y)
4. {
5. int swap;
6. swap=*x;
7. *x=*y;
8. *y=swap;
9. }
10. int main()
11. {
12. int x=500, y=100;
13. swap(&x, &y); // passing value to function
14. cout<<"Value of x is: "<<x<<endl;
15. cout<<"Value of y is: "<<y<<endl;
16. return 0;
17. }
Output:
2 Changes made inside the function is not Changes made inside the function is
reflected on other functions reflected outside the function also
3 Actual and formal arguments will be Actual and formal arguments will be
created in different memory location created in same memory location
C++ Recursion
When function is called within the same function, it is known as recursion in C++. The
function which calls the same function, is known as recursive function.
A function that calls itself, and doesn't perform any task after function call, is known as tail
recursion. In tail recursion, we generally call the same function with return statement.
1. recursionfunction(){
2. recursionfunction(); //calling self function
3. }
C++ Recursion Example
Let's see an example to print factorial number using recursion in C++ language.
1. #include<iostream>
2. using namespace std;
3. int main()
4. {
5. int factorial(int);
6. int fact,value;
7. cout<<"Enter any number: ";
8. cin>>value;
9. fact=factorial(value);
10. cout<<"Factorial of a number is: "<<fact<<endl;
11. return 0;
12. }
13. int factorial(int n)
14. {
15. if(n<0)
16. return(-1); /*Wrong value*/
17. if(n==0)
18. return(1); /*Terminating condition*/
19. else
20. {
21. return(n*factorial(n-1));
22. }
23. }
Output:
Lifetime refers to the period during which the variable remains active and visibility refers to
the module of a program in which the variable is accessible.
There are five types of storage classes, which can be used in a C++ program
1. Automatic
2. Register
3. Static
4. External
5. Mutable
It is the default storage class for all local variables. The auto keyword is applied to all local
variables automatically.
1. {
2. auto int y;
3. float y = 3.45;
4. }
The above example defines two variables with a same storage class, auto can only be used
within functions.
The register variable allocates memory in register than RAM. Its size is same of register size.
It has a faster access than other variables.
It is recommended to use register variable only for quick access such as in counter.
The static variable has the default value 0 which is provided by compiler.
1. #include <iostream>
2. using namespace std;
3. void func() {
4. static int i=0; //static variable
5. int j=0; //local variable
6. i++;
7. j++;
8. cout<<"i=" << i<<" and j=" <<j<<endl;
9. }
10. int main()
11. {
12. func();
13. func();
14. func();
15. }
Output:
i= 1 and j= 1
i= 2 and j= 1
i= 3 and j= 1
The extern variable is visible to all the programs. It is used if two or more files are sharing
same variable or function.
LECTURE FOUR
C++ Arrays
Like other programming languages, array in C++ is a group of similar types of elements that
have contiguous memory location.
In C++ std::array is a container that encapsulates fixed size arrays. In C++, array index starts
from 0. We can store only fixed set of elements in C++ array.
o Fixed size
Array declaration
Syntax
Data-type arrayName[size]; or
For example
Let's see a simple example of C++ array, where we are going to create, initialize and traverse
array.
1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. int arr[5]={10, 0, 20, 0, 30}; //creating and initializing array
6. //traversing array
7. for (int i = 0; i < 5; i++)
8. {
9. cout<<arr[i]<<"\n";
10. }
11. }
Output:/p>
10
0
20
0
30
1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. int arr[5]={10, 0, 20, 0, 30}; //creating and initializing array
6. //traversing array
7. for (int i: arr)
8. {
9. cout<<i<<"\n";
10. }
11. }
Output:
10
20
30
40
50
In C++, to reuse the array logic, we can create function. To pass array to function in C++, we
need to provide only array name.
Let's see an example of C++ function which prints the array elements.
1. #include <iostream>
2. using namespace std;
3. void printArray(int arr[5]);
4. int main()
5. {
6. int arr1[5] = { 10, 20, 30, 40, 50 };
7. int arr2[5] = { 5, 15, 25, 35, 45 };
8. printArray(arr1); //passing array to function
9. printArray(arr2);
10. }
11. void printArray(int arr[5])
12. {
13. cout << "Printing array elements:"<< endl;
14. for (int i = 0; i < 5; i++)
15. {
16. cout<<arr[i]<<"\n";
17. }
18. }
Output:
Let's see an example of C++ array which prints minimum number in an array using function.
1. #include <iostream>
2. using namespace std;
3. void printMin(int arr[5]);
4. int main()
5. {
6. int arr1[5] = { 30, 10, 20, 40, 50 };
7. int arr2[5] = { 5, 15, 25, 35, 45 };
8. printMin(arr1);//passing array to function
9. printMin(arr2);
10. }
11. void printMin(int arr[5])
12. {
13. int min = arr[0];
14. for (int i = 0; i > 5; i++)
15. {
16. if (min > arr[i])
17. {
18. min = arr[i];
19. }
20. }
21. cout<< "Minimum element is: "<< min <<"\n";
22. }
Output:
Let's see an example of C++ array which prints maximum number in an array using function.
1. #include <iostream>
2. using namespace std;
3. void printMax(int arr[5]);
4. int main()
5. {
6. int arr1[5] = { 25, 10, 54, 15, 40 };
7. int arr2[5] = { 12, 23, 44, 67, 54 };
8. printMax(arr1); //Passing array to function
9. printMax(arr2);
10. }
11. void printMax(int arr[5])
12. {
13. int max = arr[0];
14. for (int i = 0; i < 5; i++)
15. {
16. if (max < arr[i])
17. {
18. max = arr[i];
19. }
20. }
21. cout<< "Maximum element is: "<< max <<"\n";
22. }
Output:
The multidimensional array is also known as rectangular arrays in C++. It can be two
dimensional or three dimensional. The data is stored in tabular form (row ∗ column) which is
also known as matrix.
1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. int test[3][3]; //declaration of 2D array
6. test[0][0]=5; //initialization
7. test[0][1]=10;
8. test[1][1]=15;
9. test[1][2]=20;
10. test[2][0]=30;
11. test[2][2]=10;
12. //traversal
13. for(int i = 0; i < 3; ++i)
14. {
15. for(int j = 0; j < 3; ++j)
16. {
17. cout<< test[i][j]<<" ";
18. }
19. cout<<"\n"; //new line at each row
20. }
21. return 0;
22. }
Output:
5 10 0
0 15 20
30 0 10
1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. int test[3][3] =
6. {
7. {2, 5, 5},
8. {4, 0, 3},
9. {9, 1, 8} }; //declaration and initialization
10. //traversal
11. for(int i = 0; i < 3; ++i)
12. {
13. for(int j = 0; j < 3; ++j)
14. {
15. cout<< test[i][j]<<" ";
16. }
17. cout<<"\n"; //new line at each row
18. }
19. return 0;
20. }
Output:"
255
403
918
CHAPTER THREE CLASSES AND OBJECTS C++
Classes and objects are the two main aspects of object-oriented programming.
Look at the following illustration to see the difference between class and objects:
Another example
When the individual objects are created, they inherit all the variables and functions from the
class.
C++ Classes/Objects
Everything in C++ is associated with classes and objects, along with its attributes and
methods. For example: in real life, a car is an object. The car has attributes, such as weight
and color, and methods, such as drive and brake.
Attributes and methods are basically variables and functions that belongs to the class. These
are often referred to as "class members".
A class is a user-defined data type that we can use in our program, and it works as an object
constructor, or a "blueprint" for creating objects.
Create a Class
Example
Example explained
Create an Object
In C++, an object is created from a class. We have already created the class named MyClass,
so now we can use this to create objects.
To create an object of MyClass, specify the class name, followed by the object name.
To access the class attributes (myNum and myString), use the dot syntax (.) on the object:
Example
int main() {
MyClass myObj; // Create an object of MyClass
Multiple Objects
You can create multiple objects of one class:
Example
// Create a Car class with some attributes
class Car {
public:
string brand;
string model;
int year;
};
int main() {
// Create an object of Car
Car carObj1;
carObj1.brand = "BMW";
carObj1.model = "X5";
carObj1.year = 1999;
Class Methods
In the following example, we define a function inside the class, and we name it "myMethod".
Note: You access methods just like you access attributes; by creating an object of the class
and using the dot syntax (.):
Inside Example
class MyClass { // The class
public: // Access specifier
void myMethod() { // Method/function defined inside the class
cout << "Hello World!";
}
};
int main() {
MyClass myObj; // Create an object of MyClass
myObj.myMethod(); // Call the method
return 0;
}
Try it Yourself »
To define a function outside the class definition, you have to declare it inside the class and
then define it outside of the class. This is done by specifiying the name of the class, followed
the scope resolution :: operator, followed by the name of the function:
Outside Example
class MyClass { // The class
public: // Access specifier
void myMethod(); // Method/function declaration
};
// Method/function definition outside the class
void MyClass::myMethod() {
cout << "Hello World!";
}
int main() {
MyClass myObj; // Create an object of MyClass
myObj.myMethod(); // Call the method
return 0;
}
Parameters
Example
#include <iostream>
using namespace std;
class Car {
public:
int speed(int maxSpeed);
};
int main() {
Car myObj; // Create an object of Car
cout << myObj.speed(200); // Call the method with an argument
return 0;
}
C++ Constructors
Constructors
To create a constructor, use the same name as the class, followed by parentheses ():
Example
class MyClass { // The class
public: // Access specifier
MyClass() { // Constructor
cout << "Hello World!";
}
};
int main() {
MyClass myObj; // Create an object of MyClass (this will call the constructor)
return 0;
}
Constructor Parameters
Constructors can also take parameters (just like regular functions), which can be useful for
setting initial values for attributes.
The following class have brand, model and year attributes, and a constructor with different
parameters. Inside the constructor we set the attributes equal to the constructor parameters
(brand=x, etc). When we call the constructor (by creating an object of the class), we pass
parameters to the constructor, which will set the value of the corresponding attributes to the
same:
Example
class Car { // The class
public: // Access specifier
string brand; // Attribute
string model; // Attribute
int year; // Attribute
Car(string x, string y, int z) { // Constructor with parameters
brand = x;
model = y;
year = z;
}
};
int main() {
// Create Car objects and call the constructor with different values
Car carObj1("BMW", "X5", 1999);
Car carObj2("Ford", "Mustang", 1969);
// Print values
cout << carObj1.brand << " " << carObj1.model << " " << carObj1.year << "\n";
cout << carObj2.brand << " " << carObj2.model << " " << carObj2.year << "\n";
return 0;
}
Just like functions, constructors can also be defined outside the class. First, declare the
constructor inside the class, and then define it outside of the class by specifying the name of
the class, followed by the scope resolution :: operator, followed by the name of the
constructor (which is the same as the class):
Example
class Car { // The class
public: // Access specifier
string brand; // Attribute
string model; // Attribute
int year; // Attribute
Car(string x, string y, int z); // Constructor declaration
};
int main() {
// Create Car objects and call the constructor with different values
Car carObj1("BMW", "X5", 1999);
Car carObj2("Ford", "Mustang", 1969);
// Print values
cout << carObj1.brand << " " << carObj1.model << " " << carObj1.year << "\n";
cout << carObj2.brand << " " << carObj2.model << " " << carObj2.year << "\n";
return 0;
}
Access Specifiers
By now, you are quite familiar with the public keyword that appears in all of our class
examples:
Example
class MyClass { // The class
public: // Access specifier
// class members goes here
};
The public keyword is an access specifier. Access specifiers define how the members
(attributes and methods) of a class can be accessed. In the example above, the members
are public - which means that they can be accessed and modified from outside the code.
However, what if we want members to be private and hidden from the outside world?
Example
class MyClass {
public: // Public access specifier
int x; // Public attribute
private: // Private access specifier
int y; // Private attribute
};
int main() {
MyClass myObj;
myObj.x = 25; // Allowed (public)
myObj.y = 50; // Not allowed (private)
return 0;
}
Tip: It is considered good practice to declare your class attributes as private (as often as you
can). This will reduce the possibility of yourself (or others) to mess up the code. This is also
the main ingredient of the Encapsulation concept, which you will learn more about in the next
chapter.
Note: By default, all members of a class are private if you don't specify an access specifier:
Example
class MyClass {
int x; // Private attribute
int y; // Private attribute
};
C++ Encapsulation
Encapsulation
The meaning of Encapsulation, is to make sure that "sensitive" data is hidden from users. To
achieve this, you must declare class variables/attributes as private (cannot be accessed from
outside the class). If you want others to read or modify the value of a private member, you
can provide public get and set methods.
Example
#include <iostream>
using namespace std;
class Employee {
private:
// Private attribute
int salary;
public:
// Setter
void setSalary(int s) {
salary = s;
}
// Getter
int getSalary() {
return salary;
}
};
int main() {
Employee myObj;
myObj.setSalary(50000);
cout << myObj.getSalary();
return 0;
}
Example explained
The public setSalary() method takes a parameter (s) and assigns it to the salary attribute
(salary = s).
The public getSalary() method returns the value of the private salary attribute.
Inside main(), we create an object of the Employee class. Now we can use
the setSalary() method to set the value of the private attribute to 50000. Then we call
the getSalary() method on the object to return the value.
Why Encapsulation?
It is considered good practice to declare your class attributes as private (as often as
you can). Encapsulation ensures better control of your data, because you (or others)
can change one part of the code without affecting other parts
Increased security of data
C++ Inheritance
Inheritance
In C++, it is possible to inherit attributes and methods from one class to another. We group
the "inheritance concept" into two categories:
derived class (child) - the class that inherits from another class
base class (parent) - the class being inherited from
In the example below, the Car class (child) inherits the attributes and methods from
the Vehicle class (parent):
Example
// Base class
class Vehicle {
public:
string brand = "Ford";
void honk() {
cout << "Tuut, tuut! \n" ;
}
};
// Derived class
class Car: public Vehicle {
public:
string model = "Mustang";
};
int main() {
Car myCar;
myCar.honk();
cout << myCar.brand + " " + myCar.model;
return 0;
}
- It is useful for code reusability: reuse attributes and methods of an existing class when you
create a new class.
Multilevel Inheritance
A class can also be derived from one class, which is already derived from another class.
In the following example, MyGrandChild is derived from class MyChild (which is derived
from MyClass).
Example
// Base class (parent)
class MyClass {
public:
void myFunction() {
cout << "Some content in parent class." ;
}
};
int main() {
MyGrandChild myObj;
myObj.myFunction();
return 0;
}
Multiple Inheritance
A class can also be derived from more than one base class, using a comma-separated list:
Example
// Base class
class MyClass {
public:
void myFunction() {
cout << "Some content in parent class." ;
}
};
// Another base class
class MyOtherClass {
public:
void myOtherFunction() {
cout << "Some content in another class." ;
}
};
// Derived class
class MyChildClass: public MyClass, public MyOtherClass {
};
int main() {
MyChildClass myObj;
myObj.myFunction();
myObj.myOtherFunction();
return 0;
}
Access Specifiers
You learned from the Access Specifiers chapter that there are three specifiers available in
C++. Until now, we have only used public (members of a class are accessible from outside
the class) and private (members can only be accessed within the class). The third
specifier, protected, is similar to private, but it can also be accessed in the inherited class:
Example
// Base class
class Employee {
protected: // Protected access specifier
int salary;
};
// Derived class
class Programmer: public Employee {
public:
int bonus;
void setSalary(int s) {
salary = s;
}
int getSalary() {
return salary;
}
};
int main() {
Programmer myObj;
myObj.setSalary(50000);
myObj.bonus = 15000;
cout << "Salary: " << myObj.getSalary() << "\n";
cout << "Bonus: " << myObj.bonus << "\n";
return 0;
}
C++ Polymorphism
Polymorphism
Polymorphism means "many forms", and it occurs when we have many classes that are
related to each other by inheritance.
Like we specified in the previous chapter; Inheritance lets us inherit attributes and methods
from another class. Polymorphism uses those methods to perform different tasks. This
allows us to perform a single action in different ways.
For example, think of a base class called Animal that has a method called animalSound().
Derived classes of Animals could be Pigs, Cats, Dogs, Birds - And they also have their own
implementation of an animal sound (the pig oinks, and the cat meows, etc.):
Example
// Base class
class Animal {
public:
void animalSound() {
cout << "The animal makes a sound \n";
}
};
// Derived class
class Pig : public Animal {
public:
void animalSound() {
cout << "The pig says: wee wee \n";
}
};
// Derived class
class Dog : public Animal {
public:
void animalSound() {
cout << "The dog says: bow wow \n";
}
};
Remember from the Inheritance chapter that we use the : symbol to inherit from a class.
Now we can create Pig and Dog objects and override the animalSound() method:
Example
// Base class
class Animal {
public:
void animalSound() {
cout << "The animal makes a sound \n";
}
};
// Derived class
class Pig : public Animal {
public:
void animalSound() {
cout << "The pig says: wee wee \n";
}
};
// Derived class
class Dog : public Animal {
public:
void animalSound() {
cout << "The dog says: bow wow \n";
}
};
int main() {
Animal myAnimal;
Pig myPig;
Dog myDog;
myAnimal.animalSound();
myPig.animalSound();
myDog.animalSound();
return 0;
}
- It is useful for code reusability: reuse attributes and methods of an existing class when you
create a new class.
C++ Files
C++ Files
To use the fstream library, include both the standard <iostream> AND the <fstream> header
file:
Example
#include <iostream>
#include <fstream>
There are three classes included in the fstream library, which are used to create, write or read
files:
Class Description
fstream A combination of ofstream and ifstream: creates, reads, and writes to files
Create and Write To a File
To create a file, use either the ofstream or fstream class, and specify the name of the file.
Example
#include <iostream>
#include <fstream>
using namespace std;
int main() {
// Create and open a text file
ofstream MyFile("filename.txt");
Read a File
To read from a file, use either the ifstream or fstream class, and the name of the file.
Note that we also use a while loop together with the getline() function (which belongs to
the ifstream class) to read the file line by line, and to print the content of the file:
Example
// Create a text string, which is used to output the text file
string myText;
// Read from the text file
ifstream MyReadFile("filename.txt");
// Use a while loop together with the getline() function to read the file line by line
while (getline (MyReadFile, myText)) {
// Output the text from the file
cout << myText;
}