Programming Lesson by Slidesgo
Programming Lesson by Slidesgo
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.
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
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.
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>
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>
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>
int main() {
int num, sum;
sum = 0;
C++ for loop
cout << "Enter a positive integer: ";
cin >> num;
return 0;
}
C++ while loop
// C++ Program to print numbers from 1 to 5
#include <iostream>
using namespace std;
int main() {
int i = 1;
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;
#include <iostream>
using namespace std;
int main() {
int number = 0;
int sum = 0;
C++ do...while loop
do {
sum += number;
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
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;
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
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;
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
};
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);
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:
int main() {
// create an object of Wall class
Wall wall1(10.5, 8.6);
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.
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;
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;
}
};
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;
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
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;
}
};
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
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
Mars
Despite being red,
Mars is a cold place
Saturn
Saturn is a gas giant
and has several rings
PROCESS
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
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!