0% found this document useful (0 votes)
70 views204 pages

Programming Lesson by Slidesgo

C++ is a popular cross-platform language used to create high-performance applications. It was created as an extension to C and gives programmers high-level control over system resources. Some key features include being object-oriented, portable, and having a clear structure. The document provides an introduction to C++ including syntax examples and explanations of comments, variables, data types, operators, and input/output.

Uploaded by

gashaw mekonnen
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
0% found this document useful (0 votes)
70 views204 pages

Programming Lesson by Slidesgo

C++ is a popular cross-platform language used to create high-performance applications. It was created as an extension to C and gives programmers high-level control over system resources. Some key features include being object-oriented, portable, and having a clear structure. The document provides an introduction to C++ including syntax examples and explanations of comments, variables, data types, operators, and input/output.

Uploaded by

gashaw mekonnen
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1/ 204

C++ 

Introduction
What is C++?
1. C++ is a cross-platform language that can be used to
create high-performance applications.
2. C++ was developed by Bjarne Stroustrup, as an
extension to the C language.
3. C++ gives programmers a high level of control over
system resources and memory.
4. The language was updated 4 major times in 2011, 2014,
2017, and 2020 to C++11, C++14, C++17, C++20.
Why Use C++
1. C++ is one of the world's most popular programming
languages.
2. C++ can be found in today's operating systems,
Graphical User Interfaces, and embedded systems.
3. C++ is an object-oriented programming language which
gives a clear structure to programs and allows code to be
reused, lowering development costs.
4. C++ is portable and can be used to develop applications
that can be adapted to multiple platforms.
C++ Syntax

#include <iostream>
using namespace std;

int main() {
  cout << "Hello World!";
  return 0;
}
Line 1: #include <iostream> is a header file library that lets us work
with input and output objects, such as cout (used in line 5). Header files
add functionality to C++ programs.
Line 2: using namespace std means that we can use names for objects
and variables from the standard library.
Line 3: A blank line. C++ ignores white space. But we use it to make the
code more readable.

Line 4: Another thing that always appear in a C++ program, is int


main(). This is called a function. Any code inside its curly
brackets {} will be executed.
Line 5: cout (pronounced "see-out") is an object used together
with the insertion operator (<<) to output/print text. In our
example it will output "Hello World".
Note: Every C++ statement ends with a semicolon ;.
Note: The body of int main() could also been written as:
int main () { cout << "Hello World! "; return 0; }
Remember: The compiler ignores white spaces. However,
multiple lines makes the code more readable.
Line 6: return 0 ends the main function.
Line 7: Do not forget to add the closing curly bracket } to
actually end the main function.
C++ Comments
Single-line Comments
Single-line comments start with two forward slashes (//).
Any text between // and the end of the line is ignored by the compiler (will not
be executed).
This example uses a single-line comment before a line of code:
// This is a comment
cout << "Hello World!";

C++ Multi-line Comments


Multi-line comments start with /* and ends with */.
Any text between /* and */ will be ignored by the compiler:
/* The code below will print the words Hello World!
to the screen, and it is amazing */
cout << "Hello World!";
C++ Variables
Variables are containers for storing data values.
int - stores integers (whole numbers), without decimals, such as 123 or -123
double - stores floating point numbers, with decimals, such as 19.99 or -19.99
char - stores single characters, such as 'a' or 'B'. Char values are surrounded by
single quotes
string - stores text, such as "Hello World". String values are surrounded by
double quotes
bool - stores values with two states: true or false
Declaring (Creating) Variables
To create a variable, specify the type and assign it a value:
Syntax
type variableName = value;
Where type is one of C++ types (such as int), and variableName is the name of
the variable (such as x or myName). The equal sign is used to assign values
to the variable.

Example
Create a variable called myNum of type int and assign it the
value 15:
int myNum = 15;
cout << myNum;
C++ User Input
You have already learned that cout is used to output (print) values. Now
we will use cin to get user input.
cin is a predefined variable that reads data from the keyboard with the
extraction operator (>>).
In the following example, the user can input a number, which is stored
in the variable x. Then we print the value of x:
int x; 
cout << "Type a number: "; // Type a number and press enter
cin >> x; // Get user input from the keyboard
cout << "Your number is: " << x; // Display the input value
C++ Data Types
int myNum = 5;               // Integer
(whole number)
float myFloatNum = 5.99;     // Floating
point number
double myDoubleNum = 9.98;   // Floating
point number
char myLetter = 'D';         // Character
bool myBoolean = true;       // Boolean
string myText = "Hello";     // String
Basic Data Types
Data Type Size Description

boolean 1 byte Stores true or false values

char 1 byte Stores a single


character/letter/number, or ASCII
values
int 2 or 4 bytes Stores whole numbers, without
decimals
float 4 bytes Stores fractional numbers,
containing one or more decimals.
Sufficient for storing 6-7 decimal
digits
double 8 bytes Stores fractional numbers,
containing one or more decimals.
Sufficient for storing 15 decimal
digits
C++ Numeric Data Types
Numeric Types
Use int when you need to store a whole number without decimals, like 35 or
1000, and float or double when you need a floating point number (with
decimals), like 9.99 or 3.14515.
int
int myNum = 1000;
cout << myNum;

float
float myNum = 5.75;
cout << myNum;

double
double myNum = 19.99;
cout << myNum;
C++ Operators
Operators are used to perform operations on variables and
values.

C++ divides the operators into the following groups:


1. Arithmetic operators
2. Assignment operators
3. Relational operators
4. Logical operators
Arithmetic Operators
Arithmetic operators are used to perform common mathematical operations.
Operator Name Description

+ Adds two operands A + B will give 30

- Subtracts second operand from A - B will give -10


the first
* Multiplies both operands A * B will give 200

/ Divides numerator by de- B / A will give 2


numerator
% Modulus Operator and B % A will give 0
remainder of after an integer
division
++ Increment operator, increases A++ will give 11
integer value by one
-- Decrement operator, decreases A-- will give 9
integer value by one
Relational Operators
== Checks if the values of two (A == B) is not true.
operands are equal or not, if
yes then condition becomes
true.
!= Checks if the values of two (A != B) is true.
operands are equal or not, if
values are not equal then
condition becomes true.
> Checks if the value of left (A > B) is not true.
operand is greater than the
value of right operand, if yes
then condition becomes true.
< Checks if the value of left (A < B) is true.
operand is less than the value
of right operand, if yes then
condition becomes true.
>= Checks if the value of left (A >= B) is not true.
operand is greater than or equal
to the value of right operand, if
yes then condition becomes true.

<= Checks if the value of left (A <= B) is true.


operand is less than or equal to
the value of right operand, if yes
then condition becomes true.

== Checks if the values of two (A == B) is not true.


operands are equal or not, if yes
then condition becomes true.

>= Checks if the value of left (A >= B) is not true.


operand is greater than or equal
to the value of right operand, if
yes then condition becomes true.

<= Checks if the value of left (A <= B) is true.


operand is less than or equal to
the value of right operand, if yes
then condition becomes true.
Logical Operators
Operator Description Example

&& Called Logical AND operator. (A && B) is false.


If both the operands are non-
zero, then condition
becomes true.
|| Called Logical OR Operator. (A || B) is true.
If any of the two operands is
non-zero, then condition
becomes true.
! Called Logical NOT !(A && B) is true.
Operator. Use to reverses
the logical state of its
operand. If a condition is
true, then Logical NOT
operator will make false.
Assignment Operators
Operator Description Example

= Simple assignment operator,


C = A + B will assign value of A
Assigns values from right side
+ B into C
operands to left side operand.
+= Add AND assignment operator,
It adds right operand to the left C += A is equivalent to C = C +
operand and assign the result A
to left operand.
-= Subtract AND assignment
operator, It subtracts right
operand from the left operand C -= A is equivalent to C = C - A
and assign the result to left
operand.
*= Multiply AND assignment
operator, It multiplies right
operand with the left operand C *= A is equivalent to C = C * A
and assign the result to left
operand.
/= Divide AND assignment operator,
It divides left operand with the
right operand and assign the C /= A is equivalent to C = C / A
result to left operand.

%= Modulus AND assignment operator,


It takes modulus using two
C %= A is equivalent to C = C % A
operands and assign the result to
left operand.
<<= Left shift AND assignment operator. C <<= 2 is same as C = C << 2

>>= Right shift AND assignment


operator. C >>= 2 is same as C = C >> 2

&= Bitwise AND assignment operator. C &= 2 is same as C = C & 2

^= Bitwise exclusive OR and


assignment operator. C ^= 2 is same as C = C ^ 2

|= Bitwise inclusive OR and


assignment operator. C |= 2 is same as C = C | 2
Exercises
#include <iostream>
using namespace std;

int main() {
int x, y;
int sum;
cout << "Type a number: ";
cin >> x;
cout << "Type another number: ";
cin >> y;
sum = x + y;
cout << "Sum is: " << sum;
return 0;
}
C++ Loop Types
There may be a situation, when you need to execute a block of code
several number of times. In general, statements are executed
sequentially: The first statement in a function is executed first,
followed by the second, and so on.
Programming languages provide various control structures that allow
for more complicated execution paths.
A loop statement allows us to execute a statement or group of
statements multiple times and following is the general from of a loop
statement in most of the programming languages −
What is C++?
C++ while loop
A while loop statement repeatedly executes a target
statement as long as a given condition is true.
Syntax
The syntax of a while loop in C++ is −
While(condition) { statement(s); }
statement(s) may be a single statement or a block of
statements. The condition may be any expression, and
true is any non-zero value. The loop iterates while the
condition is true.
C++ while loop
When the condition becomes false, program control passes to the line
immediately following the loop.
C++ while loop
key point of the while loop is that the loop might not ever run. When the
condition is tested and the result is false, the loop body will be skipped and the
first statement after the while loop will be executed.
C++ while loop
#include <iostream>
using namespace std;
int main () {
// Local variable declaration:
int a = 10;
// while loop execution
while( a < 20 ) {
cout << "value of a: " << a << endl;
a++;
}
return 0;
}
C++ for loop
A for loop is a repetition control structure that allows you to efficiently
write a loop that needs to execute a specific number of times.

Syntax
The syntax of a for loop in C++ is −
for ( init; condition; increment ) {
statement(s);
}
C++ for loop
1. The init step is executed first, and only once. This step allows you to
declare and initialize any loop control variables. You are not required to
put a statement here, as long as a semicolon appears.
2. Next, the condition is evaluated. If it is true, the body of the loop is
executed. If it is false, the body of the loop does not execute and flow of
control jumps to the next statement just after the for loop.
3. After the body of the for loop executes, the flow of control jumps back
up to the increment statement. This statement can be left blank, as long
as a semicolon appears after the condition.
4. The condition is now evaluated again. If it is true, the loop executes and
the process repeats itself (body of loop, then increment step, and then
again condition). After the condition becomes false, the for loop
terminates.
C++ for loop
C++ for loop
#include <iostream>
using namespace std;
int main () {
// for loop execution
for( int a = 10; a < 20; a = a + 1 ) {
cout << "value of a: " << a << endl;
}
return 0;
}
C++ do...while loop
1. Unlike for and while loops, which test the loop condition at the top
of the loop, the do...while loop checks its condition at the bottom of
the loop.
2. A do...while loop is similar to a while loop, except that a do...while
loop is guaranteed to execute at least one time.
Syntax
The syntax of a do...while loop in C++ is −
do {
statement(s);
} while( condition );
C++ do...while loop
1. Notice that the conditional expression appears at the end of the loop,
so the statement(s) in the loop execute once before the condition is
tested.
2. If the condition is true, the flow of control jumps back up to do, and
the statement(s) in the loop execute again. This process repeats until
the given condition becomes false.
C++ do...while loop
C++ do...while loop
#include <iostream>
using namespace std;
int main () {
// Local variable declaration:
int a = 10;
// do loop execution
do { cout << "value of a: " << a << endl;
a = a + 1;
} while( a < 20 );
return 0;
}
C++ nested loops
A loop can be nested inside of another loop. C++ allows at least 256
levels of nesting.
Syntax
The syntax for a nested for loop statement in C++ is as follows −
for ( init; condition; increment ) {
for ( init; condition; increment ) {
statement(s);
}
statement(s); // you can put more statements.
}
C++ nested loops
#include <iostream>
using namespace std;
int main () {
int i, j;
for(i = 2; i<100; i++) {
for(j = 2; j <= (i/j); j++)
if(!(i%j)) break; // if factor found, not prime
if(j > (i/j)) cout << i << " is prime\n";
}
return 0;
}
C++ for loop
Example 1: Printing Numbers From 1 to 5
#include <iostream>

using namespace std;

int main() {
for (int i = 1; i <= 5; ++i) {
cout << i << " ";
}
return 0;
}
C++ for loop
Example 2: Display a text 5 times
// C++ Program to display a text 5 times

#include <iostream>

using namespace std;

int main() {
for (int i = 1; i <= 5; ++i) {
cout << "Hello World! " << endl;
}
return 0;
}
C++ for loop
// C++ program to find the sum of first n natural numbers
// positive integers such as 1,2,3,...n are known as natural
numbers

#include <iostream>

using namespace std;

int main() {
int num, sum;
sum = 0;
C++ for loop
cout << "Enter a positive integer: ";
cin >> num;

for (int i = 1; i <= num; ++i) {


sum += i;
}

cout << "Sum = " << sum << endl;

return 0;
}
C++ while loop
// C++ Program to print numbers from 1 to 5
#include <iostream>
using namespace std;
int main() {
int i = 1;

// while loop from 1 to 5


while (i <= 5) {
cout << i << " ";
++i;
}

return 0;
}
C++ while loop
// program to find the sum of positive numbers
// if the user enters a negative number, the loop ends
// the negative number entered is not added to the sum

#include <iostream>
using namespace std;

int main() {
int number;
int sum = 0;

// take input from the user


C++ while loop
cout << "Enter a number: ";
cin >> number;

while (number >= 0) {


// add all positive numbers
sum += number;
// take input again if the number is positive
cout << "Enter a number: ";
cin >> number;
}
// display the sum
cout << "\nThe sum is " << sum << endl;
return 0;
}
C++ do...while loop
// C++ Program to print numbers from 1 to 5
#include <iostream>
using namespace std;
int main() {
int i = 1;

// do...while loop from 1 to 5


do {
cout << i << " ";
++i;
}
while (i <= 5);
return 0;
}
C++ do...while loop
// program to find the sum of positive numbers
// If the user enters a negative number, the loop ends
// the negative number entered is not added to the sum

#include <iostream>
using namespace std;

int main() {
int number = 0;
int sum = 0;
C++ do...while loop
do {
sum += number;

// take input from the user


cout << "Enter a number: ";
cin >> number;
}
while (number >= 0);

// display the sum


cout << "\nThe sum is " << sum << endl;

return 0;
}
C++ Loop Control Statements
Loop control statements change execution from its normal sequence.
When execution leaves a scope, all automatic objects that were created in
that scope are destroyed.
1. break statement Terminates the loop or switch statement and
transfers execution to the statement immediately following the loop
or switch.
2. continue statement Causes the loop to skip the remainder of its body
and immediately retest its condition prior to reiterating.
3. goto statement Transfers control to the labeled statement. Though it
is not advised to use goto statement in your program.
C++ break statement
The break statement has the following two usages in C++ −
When the break statement is encountered inside a loop, the loop is
immediately terminated and program control resumes at the next
statement following the loop.
Syntax
The syntax of a break statement in C++ is −
break;
C++ break statement
#include <iostream>
using namespace std;
int main () {
// Local variable declaration:
int a = 10;
// do loop execution
do {
cout << "value of a: " << a << endl;
a = a + 1;
if( a > 15) {
// terminate the loop
break;
}
}
while( a < 20 );
return 0; }
C++ continue statement
1. The continue statement works somewhat like the break statement.
Instead of forcing termination, however, continue forces the next
iteration of the loop to take place, skipping any code in between.
2. For the for loop, continue causes the conditional test and increment
portions of the loop to execute. For the while and do...while loops,
program control passes to the conditional tests.
Syntax
The syntax of a continue statement in C++ is −
continue;
C++ continue statement
#include <iostream>
using namespace std;
int main () {
// Local variable declaration:
int a = 10;
// do loop execution do {
if( a == 15) {
// skip the iteration.
a = a + 1;
continue; }
cout << "value of a: " << a << endl;
a = a + 1; }
while( a < 20 );
return 0; }
C++ goto statement
1. A goto statement provides an unconditional jump from the goto to a
labeled statement in the same function.
2. NOTE − Use of goto statement is highly discouraged because it
makes difficult to trace the control flow of a program, making the
program hard to understand and hard to modify. Any program that
uses a goto can be rewritten so that it doesn't need the goto.
3. Syntax
4. The syntax of a goto statement in C++ is −
5. goto label; .. . label: statement; Where label is an identifier that
identifies a labeled statement. A labeled statement is any statement
that is preceded by an identifier followed by a colon (:).
C++ goto statement
#include <iostream>
using namespace std;
int main () {
// Local variable declaration:
int a = 10;
// do loop execution LOOP:do {
if( a == 15) {
// skip the iteration.
a = a + 1; goto LOOP; }
cout << "value of a: " << a << endl;
a = a + 1; }
while( a < 20 );
return 0; }
C++ decision making statements
Decision making structures require that the programmer specify one or
more conditions to be evaluated or tested by the program, along with a
statement or statements to be executed if the condition is determined to
be true, and optionally, other statements to be executed if the condition is
determined to be false.
C++ decision making statements
C++ decision making statements
Sr.No Statement & Description

1 if statementAn ‘if’ statement consists of a boolean expression followed by one or


more statements.

2 if...else statementAn ‘if’ statement can be followed by an optional ‘else’ statement,


which executes when the boolean expression is false.

3 switch statementA ‘switch’ statement allows a variable to be tested for equality


against a list of values.

4 nested if statementsYou can use one ‘if’ or ‘else if’ statement inside another ‘if’ or
‘else if’ statement(s).

5 nested switch statementsYou can use one ‘switch’ statement inside another ‘switch’
statement(s).
C++ if statement
An if statement consists of a boolean expression followed by one or
more statements.
Syntax
The syntax of an if statement in C++ is −
if(boolean_expression) {
// statement(s) will execute if the boolean expression is true
}
If the boolean expression evaluates to true, then the block of code
inside the if statement will be executed. If boolean expression
evaluates to false, then the first set of code after the end of the if
statement (after the closing curly brace) will be executed.
C++ if statement
C++ if statement
#include <iostream>
using namespace std;
int main () {
// local variable declaration:
int a = 10;
// check the boolean condition
if( a < 20 ) {
// if condition is true then print the following
cout << "a is less than 20;" << endl;
}
cout << "value of a is : " << a << endl;
return 0;
}
C++ if statement
// Program to print positive number entered by the user
// If the user enters a negative number, it is skipped
#include <iostream>
using namespace std;
int main() {
int number;
cout << "Enter an integer: ";
cin >> number;
// checks if the number is positive
if (number > 0) {
cout << "You entered a positive integer: " << number << endl;
}
cout << "This statement is always executed.";
return 0; }
C++ if...else statement
An if statement can be followed by an optional else statement, which
executes when the boolean expression is false.
Syntax
The syntax of an if...else statement in C++ is −
if(boolean_expression) {
// statement(s) will execute if the boolean expression is true
} else {
// statement(s) will execute if the boolean expression is false
}
If the boolean expression evaluates to true, then the if block of code
will be executed, otherwise else block of code will be executed.
C++ if...else statement
C++ if...else statement
#include <iostream>
using namespace std;
int main () {
// local variable declaration:
int a = 100;
// check the boolean condition
if( a < 20 ) {
// if condition is true then print the following
cout << "a is less than 20;" << endl;
} else {
// if condition is false then print the following
cout << "a is not less than 20;" << endl; }
cout << "value of a is : " << a << endl;
return 0;}
C++ if...else statement
// Program to check whether an integer is positive or negative
// This program considers 0 as a positive number
#include <iostream>
using namespace std;
int main() {
int number;
cout << "Enter an integer: ";
cin >> number;
if (number >= 0) {
cout << "You entered a positive integer: " << number << endl;
}
else {
cout << "You entered a negative integer: " << number << endl;
}
cout << "This line is always printed.";
return 0;
}
C++ if...else statement
// Program to check whether an integer is positive or negative
// This program considers 0 as a positive number
#include <iostream>
using namespace std;
int main() {
int number;
cout << "Enter an integer: ";
cin >> number;
if (number >= 0) {
cout << "You entered a positive integer: " << number << endl;
}
else {
cout << "You entered a negative integer: " << number << endl;
}
cout << "This line is always printed.";
return 0;
}
C++ if...else statement
// Program to check whether an integer is positive or negative
// This program considers 0 as a positive number
#include <iostream>
using namespace std;
int main() {
int number;
cout << "Enter an integer: ";
cin >> number;
if (number >= 0) {
cout << "You entered a positive integer: " << number << endl;
}
else {
cout << "You entered a negative integer: " << number << endl;
}
cout << "This line is always printed.";
return 0;
}
C++ if...else statement
// Program to check whether an integer is positive or negative
// This program considers 0 as a positive number
#include <iostream>
using namespace std;
int main() {
int number;
cout << "Enter an integer: ";
cin >> number;
if (number >= 0) {
cout << "You entered a positive integer: " << number << endl;
}
else {
cout << "You entered a negative integer: " << number << endl;
}
cout << "This line is always printed.";
return 0;
}
C++ if...else statement
// Program to check whether an integer is positive, negative or zero

#include <iostream>
using namespace std;

int main() {

int number;

cout << "Enter an integer: ";


cin >> number;
C++ if...else...else if statement
if (number > 0) {
cout << "You entered a positive integer: " << number << endl;
}
else if (number < 0) {
cout << "You entered a negative integer: " << number << endl;
}
else {
cout << "You entered 0." << endl;
}

cout << "This line is always printed.";

return 0;
}
C++ switch statement
A switch statement allows a variable to be tested for equality against a
list of values. Each value is called a case, and the variable being
switched on is checked for each case.
Syntax
The syntax for a switch statement in C++ is as follows −
switch(expression) {
case constant-expression :
statement(s);
break; //optional
case constant-expression :
statement(s); break; //optional
// you can have any number of case statements.
default : //Optional
statement(s); }
C++ switch statement
The following rules apply to a switch statement −
 The expression used in a switch statement must have an integral or
enumerated type, or be of a class type in which the class has a single
conversion function to an integral or enumerated type.
 You can have any number of case statements within a switch. Each
case is followed by the value to be compared to and a colon.
 The constant-expression for a case must be the same data type as
the variable in the switch, and it must be a constant or a literal.
C++ switch statement
 When the variable being switched on is equal to a case, the
statements following that case will execute until a break statement is
reached.
 When a break statement is reached, the switch terminates, and the
flow of control jumps to the next line following the switch
statement.
 Not every case needs to contain a break. If no break appears, the
flow of control will fall through to subsequent cases until a break is
reached.
 A switch statement can have an optional default case, which must
appear at the end of the switch. The default case can be used for
performing a task when none of the cases is true. No break is needed
in the default case.
C++ switch statement
C++ switch statement
#include <iostream>
using namespace std;
int main () {
// local variable declaration:
char grade = 'D';
switch(grade) {
case 'A' :
cout << "Excellent!" << endl;
break;
case 'B' :
case 'C' :
cout << "Well done" << endl;
break;
C++ switch statement
case 'D' :
cout << "You passed" << endl;
break;
case 'F' :
cout << "Better try again" << endl;
break;
default :
cout << "Invalid grade" << endl;
}
cout << "Your grade is " << grade << endl;
return 0;
}
C++ nested if statements
It is always legal to nest if-else statements, which means you can use
one if or else if statement inside another if or else if statement(s).
Syntax
The syntax for a nested if statement is as follows −
if( boolean_expression 1) {
// Executes when the boolean expression 1 is true if(boolean_expression
2) {
// Executes when the boolean expression 2 is true } } You can

nest else if...else in the similar way as you have nested if statement.


C++ nested if statements
An if statement can be followed by an optional else statement, which
executes when the boolean expression is false.
Syntax
The syntax of an if...else statement in C++ is −
if(boolean_expression) {
// statement(s) will execute if the boolean expression is true
} else {
// statement(s) will execute if the boolean expression is false
}
If the boolean expression evaluates to true, then the if block of code
will be executed, otherwise else block of code will be executed.
C++ nested if statements
int mark = 100;
if (mark >= 50) {
cout << "You passed." << endl;
if (mark == 100) {
cout <<"Perfect!" << endl;
}
} else {
cout << "You failed." << endl;
}
C++ nested if statements
int age=18;
if(age>14)
{
if(age>=18)
{
cout<<"Adult";
}
else
{ cout<<"Teenager";
}
}
C++ nested if statements
else
{
if (age > 0)
{
cout<<"Child";
}
else
{
cout << "Something's wrong";
}
}
C++ FUNCTIONS
1. function is a group of statements that together perform a task. Every
C++ program has at least one function, which is main, and all the
most trivial programs can define additional functions.
2. You can divide up your code into separate functions. How you
divide up your code among different functions is up to you, but
logically the division usually is so each function performs a specific
task.
3. A function declaration tells the compiler about a function's name,
return type, and parameters. A function definition provides the
actual body of the function.
C++ FUNCTIONS
The C++ standard library provides numerous built-in functions that your
program can call. For example, function strcat to concatenate two
strings, function memcpy to copy one memory location to another
location and many more functions.

A function is knows as with various names like a method or a sub-routine


or a procedure etc.
C++ FUNCTIONS
Defining a Function:

The general form of a C++ function definition is as follows:


return_type function_nam e( param eter list )
{
body of the function
}

A C++ function definition consists of a function header and a function


body. Here are all the parts of a function:
C++ FUNCTIONS
Return Type: A function may return a value. The return_type is the
data type of the value the function returns. Some functions perform
the desired operations without returning
a value. In this case, the return_type is the keyword void.
Function Name: This is the actual name of the function. The
function name and the parameter list together constitute the
function signature.
Parameters: A parameter is like a placeholder. When a function is
invoked, you pass a value to the parameter. This value is referred to
as actual parameter or argument. The parameterlist refers to the type,
order, and number of the parameters of a function. Parameters are
optional; that is, a function may contain no parameters.
C++ FUNCTIONS
Function Body: The function body contains a collection of
statements that define what thefunction does.
Example:
Following is the source code for a function called max. This function
takes two parameters num1 and num2 and returns the maximum
between the two:
C++ FUNCTIONS
1. // function returning the max between two numbers
2. int max(int num 1, int num 2)
3. {
4. // local variable declaration
5. int result;
6. if (num 1 > num 2)
7. result = num 1;
8. else
9. result = num 2;
10.return result;
11. }
C++ FUNCTIONS
Function Declarations:
A function declaration tells the compiler about a function name and how to
call the function. The actual body of the function can be defined separately. A
function declaration has the following parts:
return_type function_name( parameter list );
For the above defined function max, following is the function declaration:
int max(int num 1, int num 2);
Parameter names are not importan in function declaration only their type is
required, so following is also valid declaration:
int max(int, int);
Function declaration is required when you define a function in one source file and
you call thatfunction in another file. In such case, you should declare the
function at the top of the file calling the function.
C++ FUNCTIONS
Calling a Function:
While creating a C++ function, you give a definition of what the
function has to do. To use a function, you will have to call or invoke
that function.
When a program calls a function, program control is transferred to the
called function. A called function performs defined task and when its
return statement is executed or when its functionending closing
brace is reached, it returns program control back to the main
program.
To call a function, you simply need to pass the required parameters
along with function name, and if function returns a value, then you
can store returned value. For example:
C++ FUNCTIONS
1. #include <iostream >
2. using nam espace std;
3. // function declaration
4. int m ax(int num 1, int num 2);
5. int m ain ()
6. {
7. // local variable declaration:
8. int a = 100;
9. int b = 200;
10.int ret;
11. // calling a function to get m ax value.
12.ret = m ax(a, b);
13.cout << "Max value is : " << ret << endl;
14.return 0;
15.}
C++ FUNCTIONS
1. // function returning the m ax between two num bers
2. int m ax(int num 1, int num 2)
3. {
4. // local variable declaration
5. int result;
6. if (num 1 > num 2)
7. result = num 1;
8. else
9. result = num 2;
10.return result;
11. }
C++ FUNCTIONS
I kept max function along with main function and compiled the source
code. While running final executable, it would produce the following
result: Max value is : 200
C++ FUNCTIONS
 Function Arguments
 If a function is to use arguments, it must declare variables that accept
the values of the arguments. These variables are called the formal
parameters of the function.
 The formal parameters behave like other local variables inside the
function and are created upon entry into the function and destroyed
upon exit.
C++ FUNCTIONS
 C++ function call by value
 The call by value method of passing arguments to a function copies
the actual value of an argument into the formal parameter of the
function. In this case, changes made to the parameter inside the
function have no effect on the argument.
 By default, C++ uses call by value to pass arguments. In general, this
means that code within a function cannot alter the arguments used to
call the function. Consider the function swap() definition as follows.
C++ FUNCTIONS
// function definition to swap the values.
void swap(int x, int y) {
int temp;

temp = x; /* save the value of x */


x = y; /* put y into x */
y = temp; /* put x into y */
return;
}
Now, let us call the function swap() by passing actual values as in the
following example −
#include <iostream>
using namespace std;
// function declaration
void swap(int x, int y);
int main () {
// local variable declaration:
int a = 100;
int b = 200;
cout << "Before swap, value of a :" << a << endl;
cout << "Before swap, value of b :" << b << endl;
// calling a function to swap the values.
swap(a, b);
cout << "After swap, value of a :" << a << endl;
cout << "After swap, value of b :" << b << endl; return 0; }
C++ FUNCTIONS
 C++ function call by pointer
 The call by pointer method of passing arguments to a function
copies the address of an argument into the formal parameter. Inside
the function, the address is used to access the actual argument used
in the call. This means that changes made to the parameter affect the
passed argument.
 To pass the value by pointer, argument pointers are passed to the
functions just like any other value. So accordingly you need to
declare the function parameters as pointer types as in the following
function swap(), which exchanges the values of the two integer
variables pointed to by its arguments.
C++ FUNCTIONS
// function definition to swap the values.
void swap(int *x, int *y) {
int temp;
temp = *x; /* save the value at address x */
*x = *y;
/* put y into x */ *y = temp;
/* put x into y */
return;
}
#include <iostream>
using namespace std;
// function declaration
void swap(int *x, int *y);
int main () {
// local variable declaration:
int a = 100; int b = 200;
cout << "Before swap, value of a :" << a << endl;
cout << "Before swap, value of b :" << b << endl;
/* calling a function to swap the values. * &a indicates pointer to a ie. address of
variable a and * &b indicates pointer to b ie. address of variable b. */
swap(&a, &b);
cout << "After swap, value of a :" << a << endl;
cout << "After swap, value of b :" << b << endl;
return 0; }
C++ FUNCTIONS
 C++ function call by reference
 The call by reference method of passing arguments to a function
copies the reference of an argument into the formal parameter. Inside
the function, the reference is used to access the actual argument used
in the call. This means that changes made to the parameter affect the
passed argument.
 To pass the value by reference, argument reference is passed to the
functions just like any other value. So accordingly you need to
declare the function parameters as reference types as in the
following function swap(), which exchanges the values of the two
integer variables pointed to by its arguments.
C++ FUNCTIONS
// function definition to swap the values.
void swap(int &x, int &y)
{ int temp; temp = x;
/* save the value at address x */
x = y;
/* put y into x */
y = temp;
/* put x into y */
return;
}
#include <iostream>
using namespace std;
// function declaration
void swap(int &x, int &y);
int main () {
// local variable declaration:
int a = 100; int b = 200;
cout << "Before swap, value of a :" << a << endl;
cout << "Before swap, value of b :" << b << endl;
/* calling a function to swap the values using variable reference.*/
swap(a, b);
cout << "After swap, value of a :" << a << endl;
cout << "After swap, value of b :" << b << endl;
return 0;
}
C++ FUNCTIONS
 Default Values for Parameters
 When you define a function, you can specify a default value for each
of the last parameters. This value will be used if the corresponding
argument is left blank when calling to the function.
 This is done by using the assignment operator and assigning values
for the arguments in the function definition. If a value for that
parameter is not passed when the function is called, the default given
value is used, but if a value is specified, this default value is ignored
and the passed value is used instead.
#include <iostream>
using namespace std;
int sum(int a, int b = 20) {
int result;
result = a + b;
return (result); }
int main () {
// local variable declaration:
int a = 100; int b = 200;
int result;
// calling a function to add the values.
result = sum(a, b);
cout << "Total value is :" << result << endl;
// calling a function again as follows.
result = sum(a);
cout << "Total value is :" << result << endl; return 0; }
C++ What is OOP?
 OOP stands for Object-Oriented Programming.
 Procedural programming is about writing procedures or functions that
perform operations on the data, while object-oriented programming is
about creating objects that contain both data and functions.
 Object-oriented programming has several advantages over procedural
programming:
 OOP is faster and easier to execute
 OOP provides a clear structure for the programs
 OOP helps to keep the C++ code DRY "Don't Repeat Yourself", and
makes the code easier to maintain, modify and debug
 OOP makes it possible to create full reusable applications with less
code and shorter development time
C++ What are Classes and Objects?
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:

Class objects
Fruit Apple
Banana
Mango
C++ Classes/Objects
 C++ Classes/Objects
 C++ is an object-oriented programming language.
 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
To create a class, use the class keyword:
Example
Create a class called "MyClass":
class MyClass {       // The class
  public:             // Access specifier
    int myNum;        // Attribute (int variable)
    string myString;  // Attribute (string variable)
};
C++ FUNCTIONS
 Example explained
 The class keyword is used to create a class called MyClass.
 The public keyword is an access specifier, which specifies that
members (attributes and methods) of the class are accessible from
outside the class. You will learn more about access specifiers later.
 Inside the class, there is an integer variable myNum and a string
variable myString. When variables are declared within a class, they
are called attributes.
 At last, end the class definition with a semicolon ;.
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:
Create an Object
class MyClass {       // The class
  public:             // Access specifier
    int myNum;        // Attribute (int variable)
    string myString;  // Attribute (string variable)
};
int main() {
  MyClass myObj;  // Create an object of MyClass
  // Access attributes and set values
  myObj.myNum = 15; 
  myObj.myString = "Some text";
  // Print attribute values
  cout << myObj.myNum << "\n";
  cout << myObj.myString;
  return 0;
}
Multiple Objects
// 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;
Multiple Objects
 // Create another object of Car
  Car carObj2;
  carObj2.brand = "Ford";
  carObj2.model = "Mustang";
  carObj2.year = 1969;

  // Print attribute values


  cout << carObj1.brand << " " << carObj1.model << " " <<
carObj1.year << "\n";
  cout << carObj2.brand << " " << carObj2.model << " " <<
carObj2.year << "\n";
  return 0;
}
C++ Class/Object
#include <iostream>

using namespace std;

class Rectangle {
public:
double length;
double width;

double area() {
return length * width;
}
};
C++ Class/Obejct
int main() {
Rectangle rect1;
rect1.length = 5.0;
rect1.width = 3.0;
cout << "The area of rect1 is: " << rect1.area() << endl;

Rectangle rect2;
rect2.length = 7.0;
rect2.width = 2.0;
cout << "The area of rect2 is: " << rect2.area() << endl;

return 0;
}
C++ Class Methods
 Class Methods
 Methods are functions that belongs to the class.
 There are two ways to define functions that belongs to a class:
 Inside class definition
 Outside class definition
 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 (.):
C++ Class Methods
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;
}
C++ Class Methods
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;
C++ Parameters
#include <iostream>
using namespace std;
class Car {
  public:
    int speed(int maxSpeed);
};
int Car::speed(int maxSpeed) {
  return maxSpeed;
}
int main() {
  Car myObj; // Create an object of Car
  cout << myObj.speed(200); // Call the method with an argument
  return 0;
}
C++ Class Methods
class Rectangle {
private:
int width;
int height;
public:
void setDimensions(int w, int h) {
width = w;
height = h;
}
int getArea() {
return width * height;
}
};
C++ Class Methods
int main() {
Rectangle myRect;
myRect.setDimensions(4, 5);
int area = myRect.getArea(); // area is 20
return 0;
}
In the main() function, an instance of the Rectangle class is created and
its setDimensions() method is called to set the width and height of
the rectangle to 4 and 5, respectively. The getArea() method is then
called on this object to calculate the area of the rectangle, which is
20.
C++ Constructors
 Constructors
 A constructor in C++ is a special method that is automatically called
when an object of a class is created.
 To create a constructor, use the same name as the class, followed by
parentheses ():
C++ Constructors
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;
}
C++ Constructors
 A constructor is a special type of member function that is called
automatically when an object is created.
 In C++, a constructor has the same name as that of the class and it
does not have a return type. For example,
class Wall {
public:
// create a constructor
Wall() {
// code
}
};
C++ Constructors
 Here, the function Wall() is a constructor of the class Wall. Notice
that the constructor
 has the same name as the class,
 does not have a return type, and
 is public
C++ Default Constructor
A constructor with no parameters is known as a 
default constructor. In the example above, Wall() is a default
constructor.
C++ Default Constructor
// C++ program to demonstrate the use of default constructor

#include <iostream>
using namespace std;

// declare a class
class Wall {
private:
double length;
C++ Default Constructor
public:
// default constructor to initialize variable
Wall() {
length = 5.5;
cout << "Creating a wall." << endl;
cout << "Length = " << length << endl;
}
};

int main() {
Wall wall1;
return 0;
}
C++ Default Constructor
 Here, when the wall1 object is created, the Wall() constructor is
called. This sets the length variable of the object to 5.5.
 Note: If we have not defined a constructor in our class, then the C++
compiler will automatically create a default constructor with an
empty code and no parameters.
C++ Parameterized Constructor
 In C++, a constructor with parameters is known as a parameterized
constructor. This is the preferred method to initialize member data.
// C++ program to calculate the area of a wall

#include <iostream>
using namespace std;

// declare a class
class Wall {
private:
double length;
double height;
C++ Parameterized Constructor
public:
// parameterized constructor to initialize variables
Wall(double len, double hgt) {
length = len;
height = hgt;
}

double calculateArea() {
return length * height;
}
};
C++ Parameterized Constructor
int main() {
// create object and initialize data members
Wall wall1(10.5, 8.6);
Wall wall2(8.5, 6.3);

cout << "Area of Wall 1: " << wall1.calculateArea() << endl;


cout << "Area of Wall 2: " << wall2.calculateArea();

return 0;
}
C++ Parameterized Constructor
 Here, we have created a parameterized constructor Wall() that has 2
parameters: double len and double hgt. The values contained in these
parameters are used to initialize the member
variables length and height.
 When we create an object of the Wall class, we pass the values for
the member variables as arguments. The code for this is:
C++ Copy Constructor
 The copy constructor in C++ is used to copy data of one object to
another.
#include <iostream>
using namespace std;

// declare a class
class Wall {
private:
double length;
double height;
C++ Copy Constructor
public:

// initialize variables with parameterized constructor


Wall(double len, double hgt) {
length = len;
height = hgt;
}

// copy constructor with a Wall object as parameter


// copies data of the obj parameter
Wall(Wall &obj) {
length = obj.length;
height = obj.height;
}
C++ Copy Constructor
double calculateArea() {
return length * height;
}
};

int main() {
// create an object of Wall class
Wall wall1(10.5, 8.6);

// copy contents of wall1 to wall2


Wall wall2 = wall1;
C++ Copy Constructor
// print areas of wall1 and wall2
cout << "Area of Wall 1: " << wall1.calculateArea() << endl;
cout << "Area of Wall 2: " << wall2.calculateArea();

return 0;
}
C++ Inheritance
1. Inheritance is one of the key features of Object-oriented
programming in C++. It allows us to create a new class (derived
class) from an existing class (base class).
2. 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
};
C++ Inheritance
 Here, the Dog class is derived from the Animal class. Since Dog is
derived from Animal, members of Animal are accessible to Dog.
C++ Inheritance
 Notice the use of the keyword public while inheriting Dog from
Animal.
 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.
C++ Inheritance
 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
#include <iostream>
using namespace std;
// base class
class Animal {
public:
void eat() {
cout << "I can eat!" << endl;
}

void sleep() {
cout << "I can sleep!" << endl;
}
};
C++ Inheritance
// derived class
class Dog : public Animal {

public:
void bark() {
cout << "I can bark! Woof woof!!" << endl;
}
};
C++ Inheritance
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;
}
Example 2: Simple Example of C++
Inheritance
#include <iostream>
using namespace std;

// Base class
class Shape {
public:
double width;
double height;
C++ Inheritance
public:
Shape(double w, double h) {
width = w;
height = h; }
void setWidth(double w) {
width = w; }
void setHeight(double h) {
height = h; }
};
// Derived class
class Rectangle :
public Shape {
public:
Rectangle(double w, double h) : Shape(w, h) {
}
double area() {
return width * height;
}
};
int main() {
Rectangle rect(5.0, 4.0);
cout << "Area of rectangle: " << rect.area() << endl;
return 0;
}
C++ Inheritance
#include <iostream>
#include <string>
using namespace std;

// Base class
class Person {
public:
string name;
int age;
C++ Inheritance
public:
Person(string personName, int personAge) {
name = personName;
age = personAge;
}
void printInfo() {
cout << "This person is " << name << ", and is " << age << " years
old." << endl;
}
};
C++ Inheritance
// Derived class
class Student : public Person {
public:
int studentID;
string major;
public:
Student(string studentName, int studentAge, int studentIDNum,
string studentMajor) : Person(studentName, studentAge) {
studentID = studentIDNum;
major = studentMajor;
}
C++ Inheritance
void printStudentInfo() {
cout << "This student's ID is " << studentID << ", and their major
is " << major << "." << endl;
}
};

int main() {
Student myStudent("John Doe", 20, 12345, "Computer Science");
myStudent.printInfo();
myStudent.printStudentInfo();
return 0;
}
C++ Public, Protected and Private
In C++ inheritance, we can derive a child class from the base class in
different access modes. For example,
class Base {
.... ... ....
};
class Derived : public Base {
.... ... .... };
Notice the keyword public in the code
class Derived : public Base
This means that we have created a derived class from the base class
in public mode. Alternatively, we can also derive classes
in protected or private modes.
These 3 keywords (public, protected, and private) are known as access
specifiers in C++ inheritance.
public, protected and private
inheritance in C++
 public, protected, and private inheritance have the following
features:
 public inheritance makes public members of the base
class public in the derived class, and the protected members of the
base class remain protected in the derived class.
 protected inheritance makes the public and protected members of
the base class protected in the derived class.
 private inheritance makes the public and protected members of the
base class private in the derived class.
 Note: private members of the base class are inaccessible to the
derived class.
class Base { public:
int x;
protected: int y;
private: int z; };
class PublicDerived: public Base {
// x is public
// y is protected
// z is not accessible from PublicDerived };
class ProtectedDerived: protected Base {
// x is protected
// y is protected //
z is not accessible from ProtectedDerived };
class PrivateDerived: private Base {
// x is private
// y is private
// z is not accessible from PrivateDerived };
// C++ program to demonstrate the working of public inheritance

#include <iostream>
using namespace std;

class Base {
private:
int pvt = 1;

protected:
int prot = 2;

public:
int pub = 3;
Example 1: C++ public Inheritance
// function to access private member
int getPVT() {
return pvt;
}
};

class PublicDerived : public Base {


public:
// function to access protected member from Base
int getProt() {
return prot;
}
};
Example 1: C++ public Inheritance
int main() {
PublicDerived object1;
cout << "Private = " << object1.getPVT() << endl;
cout << "Protected = " << object1.getProt() << endl;
cout << "Public = " << object1.pub << endl;
return 0;
}
Output
Private = 1
Protected = 2
Public = 3
Example 1: C++ public Inheritance
 Here, we have derived PublicDerived from Base in public mode.
 As a result, in PublicDerived:
 prot is inherited as protected.
 pub and getPVT() are inherited as public.
 pvt is inaccessible since it is private in Base.
 Since private and protected members are not accessible
from main(), we need to create public
functions getPVT() and getProt() to access them:
• // Error: member "Base::pvt" is inaccessible cout << "Private = " <<
object1.pvt;
• // Error: member "Base::prot" is inaccessible cout << "Protected = "
<< object1.prot;
Example 1: C++ public Inheritance
1. Notice that the getPVT() function has been defined inside Base. But
the getProt() function has been defined inside PublicDerived.
2. This is because pvt, which is private in Base, is inaccessible
to PublicDerived.
3. However, prot is accessible to PublicDerived due to public
inheritance. So, getProt() can access the protected variable from
within PublicDerived.
Accessibility in public Inheritance

private protected public


Accessibility
members members members

Base Class Yes Yes Yes

Derived
No Yes Yes
Class
Example 2: C++ protected Inheritance
// C++ program to demonstrate the working of protected inheritance

#include <iostream>
using namespace std;

class Base {
private:
int pvt = 1;

protected:
int prot = 2;
public:
int pub = 3;

// function to access private member


int getPVT() {
return pvt;
}
};

class ProtectedDerived : protected Base {


public:
// function to access protected member from Base
int getProt() {
return prot;
}
// function to access public member from Base
int getPub() {
return pub;
}
};

int main() {
ProtectedDerived object1;
cout << "Private cannot be accessed." << endl;
cout << "Protected = " << object1.getProt() << endl;
cout << "Public = " << object1.getPub() << endl;
return 0;
}
Private cannot be accessed.
Protected = 2
Public = 3
Example 2: C++ protected Inheritance
 Here, we have derived ProtectedDerived from Base in protected
mode.
 As a result, in ProtectedDerived:
 prot, pub and getPVT() are inherited as protected.
 pvt is inaccessible since it is private in Base.
 As we know, protected members cannot be directly accessed from
outside the class. As a result, we cannot
use getPVT() from ProtectedDerived.
 That is also why we need to create the getPub() function
in ProtectedDerived in order to access the pub variable.
Example 2: C++ protected Inheritance
// Error: member "Base::getPVT()" is inaccessible
cout << "Private = " << object1.getPVT();
// Error: member "Base::pub" is inaccessible
cout << "Public = " << object1.pub;
Accessibility in protected Inheritance

private protected public


Accessibility
members members members

Base Class Yes Yes Yes

Yes (inherited
Derived Class No Yes as protected
variables)
Example 3: C++ private Inheritance
// C++ program to demonstrate the working of private inheritance

#include <iostream>
using namespace std;

class Base {
private:
int pvt = 1;

protected:
int prot = 2;

public:
int pub = 3;
Example 3: C++ private Inheritance
// function to access private member
int getPVT() {
return pvt;
}
};

class PrivateDerived : private Base {


public:
// function to access protected member from Base
int getProt() {
return prot;
}
Example 3: C++ private Inheritance
// function to access private member
int getPub() {
return pub;
}
};

int main() {
PrivateDerived object1;
cout << "Private cannot be accessed." << endl;
cout << "Protected = " << object1.getProt() << endl;
cout << "Public = " << object1.getPub() << endl;
return 0;
}
Example 3: C++ private Inheritance
Private cannot be accessed.
Protected = 2
Public = 3
Example 3: C++ private Inheritance
 Here, we have derived PrivateDerived from Base in private mode.
 As a result, in PrivateDerived:
 prot, pub and getPVT() are inherited as private.
 pvt is inaccessible since it is private in Base.
 As we know, private members cannot be directly accessed from
outside the class. As a result, we cannot
use getPVT() from PrivateDerived.
 That is also why we need to create the getPub() function
in PrivateDerived in order to access the pub variable.
Example 3: C++ private Inheritance
// Error: member "Base::getPVT()" is inaccessible
cout << "Private = " << object1.getPVT();
// Error: member "Base::pub" is inaccessible
cout << "Public = " << object1.pub;
Accessibility in private Inheritance

Accessibilit private protected public


y members members members

Base Class Yes Yes Yes

Yes Yes
Derived (inherited as (inherited as
No
Class private private
variables) variables)
Example 2: C++ protected Inheritance
 Here, we have derived ProtectedDerived from Base in protected
mode.
 As a result, in ProtectedDerived:
 prot, pub and getPVT() are inherited as protected.
 pvt is inaccessible since it is private in Base.
 As we know, protected members cannot be directly accessed from
outside the class. As a result, we cannot
use getPVT() from ProtectedDerived.
 That is also why we need to create the getPub() function
in ProtectedDerived in order to access the pub variable.
Example 2: C++ protected Inheritance
 Here, we have derived ProtectedDerived from Base in protected
mode.
 As a result, in ProtectedDerived:
 prot, pub and getPVT() are inherited as protected.
 pvt is inaccessible since it is private in Base.
 As we know, protected members cannot be directly accessed from
outside the class. As a result, we cannot
use getPVT() from ProtectedDerived.
 That is also why we need to create the getPub() function
in ProtectedDerived in order to access the pub variable.
Example 2: C++ protected Inheritance
 Here, we have derived ProtectedDerived from Base in protected
mode.
 As a result, in ProtectedDerived:
 prot, pub and getPVT() are inherited as protected.
 pvt is inaccessible since it is private in Base.
 As we know, protected members cannot be directly accessed from
outside the class. As a result, we cannot
use getPVT() from ProtectedDerived.
 That is also why we need to create the getPub() function
in ProtectedDerived in order to access the pub variable.
Example 2: C++ protected Inheritance
 Here, we have derived ProtectedDerived from Base in protected
mode.
 As a result, in ProtectedDerived:
 prot, pub and getPVT() are inherited as protected.
 pvt is inaccessible since it is private in Base.
 As we know, protected members cannot be directly accessed from
outside the class. As a result, we cannot
use getPVT() from ProtectedDerived.
 That is also why we need to create the getPub() function
in ProtectedDerived in order to access the pub variable.
Example 2: C++ protected Inheritance
 Here, we have derived ProtectedDerived from Base in protected
mode.
 As a result, in ProtectedDerived:
 prot, pub and getPVT() are inherited as protected.
 pvt is inaccessible since it is private in Base.
 As we know, protected members cannot be directly accessed from
outside the class. As a result, we cannot
use getPVT() from ProtectedDerived.
 That is also why we need to create the getPub() function
in ProtectedDerived in order to access the pub variable.
Example 2: C++ protected Inheritance
 Here, we have derived ProtectedDerived from Base in protected
mode.
 As a result, in ProtectedDerived:
 prot, pub and getPVT() are inherited as protected.
 pvt is inaccessible since it is private in Base.
 As we know, protected members cannot be directly accessed from
outside the class. As a result, we cannot
use getPVT() from ProtectedDerived.
 That is also why we need to create the getPub() function
in ProtectedDerived in order to access the pub variable.
Example 2: C++ protected Inheritance
 Here, we have derived ProtectedDerived from Base in protected
mode.
 As a result, in ProtectedDerived:
 prot, pub and getPVT() are inherited as protected.
 pvt is inaccessible since it is private in Base.
 As we know, protected members cannot be directly accessed from
outside the class. As a result, we cannot
use getPVT() from ProtectedDerived.
 That is also why we need to create the getPub() function
in ProtectedDerived in order to access the pub variable.
Example 2: C++ protected Inheritance
 Here, we have derived ProtectedDerived from Base in protected
mode.
 As a result, in ProtectedDerived:
 prot, pub and getPVT() are inherited as protected.
 pvt is inaccessible since it is private in Base.
 As we know, protected members cannot be directly accessed from
outside the class. As a result, we cannot
use getPVT() from ProtectedDerived.
 That is also why we need to create the getPub() function
in ProtectedDerived in order to access the pub variable.
Example 2: C++ protected Inheritance
 Here, we have derived ProtectedDerived from Base in protected
mode.
 As a result, in ProtectedDerived:
 prot, pub and getPVT() are inherited as protected.
 pvt is inaccessible since it is private in Base.
 As we know, protected members cannot be directly accessed from
outside the class. As a result, we cannot
use getPVT() from ProtectedDerived.
 That is also why we need to create the getPub() function
in ProtectedDerived in order to access the pub variable.
Example 2: C++ protected Inheritance
 Here, we have derived ProtectedDerived from Base in protected
mode.
 As a result, in ProtectedDerived:
 prot, pub and getPVT() are inherited as protected.
 pvt is inaccessible since it is private in Base.
 As we know, protected members cannot be directly accessed from
outside the class. As a result, we cannot
use getPVT() from ProtectedDerived.
 That is also why we need to create the getPub() function
in ProtectedDerived in order to access the pub variable.
INTRODUCTION
Mercury is the closest planet to the Sun
and the smallest one in the Solar System
—it’s only a bit larger than the Moon.
The planet’s name has nothing to do
with the liquid metal
“This is a quote, words full of wisdom that
someone important said and can make the
reader get inspired.”

—SOMEONE FAMOUS
01
OVERVIEW
ABOUT THIS TOPIC
Here you could give a brief description of the
topic you want to talk about. For example, if
you want to talk about Mercury, you could
say that it’s the smallest planet
DEFINITION OF CONCEPTS

Mercury Venus
Mercury is the closest Venus is the second planet
planet to the Sun from the Sun

Neptune Saturn
Neptune is the farthest Saturn is a gas giant and
planet from the Sun has several rings
$96,290
programming salary range

-4.30 %
ASP.NET usage is
decreasing

5,500,000
active PHP developers
FEATURES OF THE TOPIC

Mercury Venus Saturn


Mercury is the closest Venus is the second Saturn is a gas giant and
planet to the Sun planet from the Sun has several rings
20.4
million active developers use JavaScript over
other programming languages
THIS IS A TABLE

Mass Diameter Gravity

Android 1.25 0.50 13.2

HTML5 3.20 2.75 20.5

Python 50.5 10.5 12.4


DEMO

You can replace the image


on the screen with your
own work. Just move the
filter aside, delete this
0:50 / 2:50
picture, add yours and
#loremipsum #loremipsum
place the filter on top again
Lorem Ipsum Dolor Sit Amet - Lorem Ipsum Dolor
Sit
300 views

Lorem Ipsum Dolor


Sit Amet
SUBSCRIBE
2.0 M
THIS IS A MAP

Mars
Despite being red,
Mars is a cold place

Saturn
Saturn is a gas giant
and has several rings
PROCESS

Step 1 Step 2 Step 3


Mercury is the closest Venus is the second Despite being red,
planet to the Sun planet from the Sun Mars is a cold place

Step 4 Step 5 Step 6


It’s the biggest planet Saturn is the ringed one It’s the farthest planet
in the Solar System and a gas giant from the Sun
A PICTURE IS
WORTH A
THOUSAND WORDS
Solution
Despite being red, Mars is
actually a cold place

Problem
Jupiter is the biggest planet in
the Solar System
OVERVIEW DIAGRAM
Header
Mercury is the smallest planet

Nav
HTML5 Despite being red, Mars is cold

Saturn is composed of
hydrogen and helium Body
Earth is where we live on

Footer
Pluto is now a dwarf planet
OTHER CONCEPTS

Mercury Venus
It’s the closest planet to the Venus has a beautiful name
Sun and the smallest in the and is the second planet
Solar System from the Sun
PROGRAMMING TIMELINE
Jupiter is the biggest Neptune is the farthest
planet of them all planet from the Sun

iOS HTML5

1991 2007 2008 2014

Python Android
Mercury is the closest Saturn is composed of
planet to the Sun hydrogen and helium
EXERCISE

<!DOCTYPE html>
<html>
<body>

<canvas id="myCanvas"
width="250" height="25"
style="border:4px solid #00ffc5;">
</canvas>

</body>
</html>
THANKS!

CREDITS: This presentation template was created by


Slidesgo, incluiding icons by Flaticon, and
infographics & images by Freepik.

You might also like