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

C++ AND OPP

CONCEPT
Prepared by: JUNAID MALIK

Muhammad Junaid
0304-1659294
AL-JUNAID INSTITUTE of GROUP
C++ Syntax:
Various component in a C++ program
Using namespace std; ……………………………………. Namespace means and
STD means Standard name
#include <iostream> …………………………………… Library
Head inclusion
Int main () {………………………. Extension begins here Must have int as return
Type
Cout<<”Hello Junaid”; ………………….. print output
Return 0; Value must be returned at the end of main()
}

Comment:
 Comment are the lines ignored by the compiler while compilation
 To make notes, provide details etc.
 Single Line //this is a single Line comment
 Multi Line comment /*this is a Multi-Line*/

CODE:
using namespace std;
#include <iostream>
int main()
{
//this is my First program
cout<<"HELLO JUNAID";
return 0;

pg. 1
AL-JUNAID INSTITUTE of GROUP
}

Variable:
 Memory references whose value changes during execution
 Makes Memory Handling easy. Make reuse of same memory
locations for storing different values. Makes referencing of value
easier

Syntax:
Initialization:
Data_type[variable_name];
Data_type can be INT,String,character,float etc

Assignment:
[variable_name]=value;
CODE:
using namespace std;
#include <iostream>
int main()
{
int a=10;
float b=20;
cout<<a+b;
return 0;
}

CODE No 2:
using namespace std;
#include <iostream>

pg. 2
AL-JUNAID INSTITUTE of GROUP
int main()
{
char a='z';
cout<<a;
return 0;
}

CODE:
using namespace std;
#include <iostream>
int main()
{
bool a=true;
//True reperesent 1
//False represent 0
cout<<a;
return 0;
}

C++ uses a concept of stream for user input/output.


A stream is an entity where a program can either insert or
extract characters to/from. There is no need to know details about the media
Associated to the stream or any of its internal specification.

Stream
Cin Standard input stream ( we can take
output from User)

pg. 3
AL-JUNAID INSTITUTE of GROUP
Cout Standard output stream
CODE:
using namespace std;
#include <iostream>
int main()
{
int a,b;
cout<<"Enter your Number :";
cin>>a;
cout<<"Enter your Number :";
cin>>b;
cout<<"Sum of Two Numbers :"<<a+b;
}

DATA TYPE

Primitive Type
Derived:
Build in Data type
 Boolean Derived from
 Character Build in Data Type
 Integer
 Floating point  Array
 Double
 Values/void

pg. 4
AL-JUNAID INSTITUTE of GROUP
Modifiers:
A modifier is used to change the base type of a data type.
Char,int and double data types support modifiers
There are four modifiers supported by C++
 Signed
 Unsigned
 Long
 Short

CODE:
using namespace std;
#include <iostream>
int main()
{
cout<<"Size of Fundementals of Data type :\n";
cout<<"-----------------------------------\n";
cout<<"the Size of (char) : "<<sizeof(char)<<"bytes\n";
cout<<"the Size of (short) : "<<sizeof(short)<<"bytes\n";
cout<<"the Size of (long) : "<<sizeof(long)<<"bytes\n";
cout<<"the Size of (int) : "<<sizeof(int)<<"bytes\n";
cout<<"the Size of (long long) : "<<sizeof(long long)<<"bytes\n";
cout<<"the Size of (float) : "<<sizeof(float)<<"bytes\n";
cout<<"the Size of (double) : "<<sizeof(double)<<"bytes\n";
cout<<"the Size of (long double) : "<<sizeof(long double)<<"bytes\n";
cout<<"the Size of (bool) : "<<sizeof(bool)<<"bytes\n";

pg. 5
AL-JUNAID INSTITUTE of GROUP
}

Operators:
C++ support primarily 5 Types of Operator:
1. Athematic Operators:
Used for Mathematical and athematic operators
There are two types of Athematic operators
 Unary Operators-Operators that operates or works
with a single operand are unary operators.
For Example: (++, --)

CODE:
using namespace std;
#include <iostream>
int main()
{
int a,b=0;
cout<<"Enter Your first Number :";
cin>>a;
cout<<"Enter You second Number :";
cin>>b;
cout<<++a; //Pre increment
cout<<'\n';
cout <<b++; //post increment
cout<<'\n';
cout<<b;

pg. 6
AL-JUNAID INSTITUTE of GROUP
return 0;
}

 Binary Operators-Operators that operates or works


with two operands are binary operators.
For Example: (*, -, +, /)

Code:
using namespace std;
#include <iostream>
int main()
{
int a,b=0;
cout<<"Enter Your first Number :";
cin>>a;
cout<<"Enter You second Number :";
cin>>b;
cout<<"sum of number :"<<a+b;
cout<<'\n';
cout<<"subtract of number :"<<a-b;
cout<<'\n';
cout<<"Multiple of number :"<<a*b;
cout<<'\n';
cout<<"Divide of number :"<<a/b;
return 0;
}

pg. 7
AL-JUNAID INSTITUTE of GROUP
2. Relational Operator
 Used for composition of the value of two operands.
 For Example, checking for equality of operand,
whether an operand is greater than the other operand
or not etc.
 Some of relational operators are (==,>=, <=)

CODE:
using namespace std;
#include <iostream>
int main()
{
int a = 5;
int b = 9;

// false && false = false


cout << ((a == 0) && (a > b)) << endl;

// false && true = false


cout << ((a == 0) && (a < b)) << endl;

// true && false = false


cout << ((a == 5) && (a > b)) << endl;

// true && true = true


cout << ((a == 5) && (a < b)) << endl;
return 0;

pg. 8
AL-JUNAID INSTITUTE of GROUP
}
3. Logical Operators
 Used to combine two or more conditions/constrains
 Result of the operation of a logical operator is a
Boolean value either True or False
 Some Logical operators are (AND (&&), OR (||),
NOT(!))

CODE:
using namespace std;
#include <iostream>
int main()
{
bool a= true;
bool b= false;
// cout<<a&&b;
// cout <<(a&&b);
// cout <<(a&&a);
// cout <<(b&&b);
// cout <<(a||b);
// cout <<((a==b)?a:b);
cout <<((a!=b)?a:b);
return 0;
}

pg. 9
AL-JUNAID INSTITUTE of GROUP
CODE:
using namespace std;
#include <iostream>
int main()
{
int a = 5;
int b = 9;

// false && false = false


cout << ((a == 0) || (a > b)) << endl;

// false && true = true


cout << ((a == 0) || (a < b)) << endl;

// true && false = true


cout << ((a == 5) || (a > b)) << endl;

// true && true = true


cout << ((a == 5) || (a < b)) << endl;
return 0;
}

pg. 10
AL-JUNAID INSTITUTE of GROUP
4. Bitwise Operator
 Used to perform bit-level operation on the operand
 Operation are first converted to bit-level and then the
calculation is performed on the operands
 Mathematical operations such as addition, subtraction,
Multiplication etc. can be performed at bit-level for
faster processing.

CODE:
using namespace std;
#include <iostream>
int main()
{
int a = 12, b = 25;

cout << "a = " << a << endl;


cout << "b = " << b << endl;
cout << "a ^ b = " << (a ^ b) << endl;
return 0;
}

pg. 11
AL-JUNAID INSTITUTE of GROUP
5. Assignment Operators
 Used for Value assignment to a variable
 Left side operand of the assignment operator is a
variable and right side operand of the assignment
operator is a value
 The value on the right side must be of the same data-
type of variable on the left side otherwise the compiler
will raise error
 Example -, +=, -=, *=, /=

CODE:
using namespace std;
#include <iostream>
int main()
{
int x = 10;
x += 5;
cout << x;;
return 0;
}

Strings:
Strings are used to store Sequence of Characters as information. Strings can
be used by importing the “cstring” library.
Connection:
Great+ Learning = Great Learning

pg. 12
AL-JUNAID INSTITUTE of GROUP
Here Great and Learning are two strings which are concatenated.
String Functions-can be used on C-Type strings. Library to be imported “cstring”
 Strcpy(c1,c2)-copies one string into another
 Strcat(c1,c2)-concatenates c2 to c1
 Strlen(s)-return the size/length of the string

CODE:
using namespace std;
#include <cstring>
#include <iostream>
int main()
{
char str1[]="JUNAID MALIK";
char str2[12];
char str3[1];
strcpy (str2,str1);
strcpy (str3,"copy successful");
printf ("str1: %s\nstr2: %s\nstr3: %s\n",str1,str2,str3);

return 0;
}

CODE No 2:
using namespace std;
#include <cstring>

pg. 13
AL-JUNAID INSTITUTE of GROUP
#include <iostream>
int main()
{
char str[80];
strcpy (str,"these ");
strcat (str,"strings ");
strcat (str,"are ");
strcat (str,"concatenated.");
puts (str);
return 0;
}

Boolean:
The Boolean data type is used to declare a variable whose value be set
as True (1) or False (0)
To Declare such a value, you use the bool Keword
The variables can then be initialized with the string value.
A Boolean constant is used to check the state of a variables, an expression or a
function, as true or False.

CODE:
using namespace std;
#include <iostream>
int main()
{
bool machineisworking = true;

pg. 14
AL-JUNAID INSTITUTE of GROUP
cout<<"since this machine is working its value is : "
<<machineisworking<<'\n';
machineisworking=false;
cout<<"the Machine has stopped operating and "<<"Now its Value is :
"<<machineisworking <<'\n';
return 0;
}

Conditional Statements in:


Conditional Statements in C programming are used to make decisions based on
the conditions. Conditional statements execute sequentially when there is no
condition around the statements. If you put some condition for a block of
statements, the execution flow may change based on the result evaluated by the
condition. This process is called decision making in ‘C.’
 If
 Else
 Elsif

If Condition:
If the condition evaluates true, then a given set of statement is executed.
However, if the condition is false then given statement is skipped and the program
control passes to the statement.

SYNATX:
If (condition)
{
Statement 1;
Statement 2;
Statement 3;

pg. 15
AL-JUNAID INSTITUTE of GROUP
}

CODE:
using namespace std;
#include <iostream>
int main()
{
int x = 1;
int y=4;

if(x<=y){
cout<<"you are right";
}
return 0;
}

If-ELSE Statement:
In programming languages, an else statement is an alternative statement that is
executed if the result of a previous test condition evaluates to false.
using namespace std;
#include <iostream>
int main()
{
int x = 1;
int y=4;

pg. 16
AL-JUNAID INSTITUTE of GROUP
if(x==y){
cout<<"you are right";
}
else{
cout<<"Sorry";
}
return 0;
}

Nested If-Else Statement:


A nested If-else statement contains one or more if-else statement. The
if else can be nested in three different ways, which are discussed here.

CODE:
using namespace std;
#include <iostream>
int main()
{
int x = 3;
int y=4;

if(x>=y)
{
if(x==1)
{

pg. 17
AL-JUNAID INSTITUTE of GROUP
cout<<"you are perefct";
}
else
{
printf("you are normal");
}
}
else
{
printf("SORRY");
}
return 0;
}

Code No 2:
using namespace std;
#include <iostream>
int main()
{
int x=20;
int y=30;
int z=50;
if(x>y){
if(x>z){
cout<<"x is greatest";

pg. 18
AL-JUNAID INSTITUTE of GROUP
}
}
else
{
if(y>z){
cout<<"y is greatest";
}
else{
cout<<"z is greatest";
}
}
return 0;
}

Switch Statement:
The Switch statement work as a multiway branch statement.
Modified from if-else
It’s a common alternative to the if statement when you want to get multiple results.
Default condition gets executed when no condition are met.
For-Example:
switch(expression) {
case x:
// code block
break;
case y:
// code block

pg. 19
AL-JUNAID INSTITUTE of GROUP
break;
default:
// code block
}

CODE:
using namespace std;
#include <iostream>
int main()
{
int day = 5;
switch (day) {
case 1:
cout << "Monday";
break;
case 2:
cout << "Tuesday";
break;
case 3:
cout << "Wednesday";
break;
case 4:
cout << "Thursday";
break;
case 5:
cout << "Friday";

pg. 20
AL-JUNAID INSTITUTE of GROUP
break;
case 6:
cout << "Saturday";
break;
case 7:
cout << "Sunday";
break;
}
return 0;
}

LOOPS:
Loops are used to re-execute a part of code a given number of time
depending upon the condition specified.
It has two types:
Entry controlled:
The condition is checked each-time before entering the loop. If
the condition is satisfied, then only the loop body executed. The loop body does
not get executed if the condition is false in the first iteration.
It has two types:
1. For Loop:
Syntax:
For (x-0;x<n; x++){
//CODE
}

pg. 21
AL-JUNAID INSTITUTE of GROUP
CODE:
using namespace std;
#include <iostream>
int main()
{
for(int x=5; x<10; x++){
cout<<x<<'\n';
}
return 0;
}
2. While Loop:
Syntax:
While (condition is true)
{
//CODE
}

CODE:
using namespace std;
#include <iostream>
int main()
{
int x=0;
while(x<5){
cout<<x<<'\n';

pg. 22
AL-JUNAID INSTITUTE of GROUP
x++;
}
return 0;
}

Do-While Loop:
The do/while loop is a variant of the while loop. This loop will execute the code
block once, before checking if the condition is true, then it will repeat the loop as
long as the condition is true.
Syntax:
do {
// code block to be executed
}
while (condition);

CODE:
using namespace std;
#include <iostream>
int main()
{
int x=0;
do{
cout<<x<<'\n';
x++;
}
while(x<5);
return 0;

pg. 23
AL-JUNAID INSTITUTE of GROUP
}
Break and Continuous Statement:

You have already seen the break statement used in an earlier chapter of this
tutorial. It was used to "jump out" of a switch statement.

The break statement can also be used to jump out of a loop.

CODE:
using namespace std;

#include <iostream>

int main()

for(int x=0; x<10; x++){

if(x==4){

break;

cout<<x<<'\n';

return 0;

pg. 24
AL-JUNAID INSTITUTE of GROUP
ARRAY:
An Array is a condition of elements of similar data type which are
stored in contiguous memory location.
Every element in an array has a specific index.
Size of array in C++ is fixed at the time of definition.

Array has two types


 Singular-Dimensional
 Multi-Dimensional

Definition:
An array can be defined in the following manner in C++
Data_type<name_of_array[size_of_array]
Size of an array must be an integer as it show the number of element in an array
which cannot be a real number.
SYNTAX:
Int a[10]; //single-dimensional
Int b[10][10]; //Double-dimensional
Array Initialization:
1. Static Initialization
Int a[10]={0,1,2,3,4,5,6,7,8,9,10}
Char c[5] = {a,e,I,o,u}

CODE:
using namespace std;
#include <iostream>

pg. 25
AL-JUNAID INSTITUTE of GROUP
int main()
{
string a[10]={"junaid","Malik","Ali","Ahmad"};
cout<< a[3];
return 0;
}

CODE No 2:
using namespace std;
#include <iostream>
int main()
{
int a[10]={1,2,3,4,5,656,7};
cout<< a[3];
return 0;
}

CODE No 3:
using namespace std;
#include <iostream>
int main()
{
int a[5] = {1,2,3,4,5};
for(int i=0; i<5;i++)
cout<<a[i]<<'\n';
string x[5]={"junaid","Malik","Ali","Ahmad"};

pg. 26
AL-JUNAID INSTITUTE of GROUP
for (int i=0;i<2;i++)
cout << i<< ":" <<x[i]<<'\n';
return 0;
}

2. Dynamic Initialization
Int a[10]; //array is created with garbage Value
For (int x=0; x<any number; <x++)
Cin>> a[x];

using namespace std;


#include <iostream>
int main()
{
int a[5];
for(int x=0; x<5;x++){
cin>>a[x];
}

for(int x=0; x<5; x++){


cout<<a[x];
}
return 0;
}

pg. 27
AL-JUNAID INSTITUTE of GROUP
CODE No 2:
using namespace std;
#include <iostream>
int main()
{
string a[5];
a[0]="junaid";
a[1]="Malik";
a[2]="Ali";
a[3]="Usama";
a[4]="uswan";
for(int x=0; x<4;x++){
cout<<x[a]<<'\n';
}
return 0;
}

pg. 28
AL-JUNAID INSTITUTE of GROUP
Pointers in C++:
Pointers are variables which store the address of a variables.
They have data type just like variables for Example an integers type pointer can
hold the address of an integer variables and an character type pointer hold the
address of char Variables.

SYNTAX:
Int a = 10;
Int *ptr=&a;
Ptr means Pointer
&a means addresses of Variables
string name = "JUNAID MALIL"; // A name variable of type string
string* ptr = &name; // A pointer variable, with the name ptr, that stores the
address of food

// Output the value of name (JUNAID MALIK)


cout << name << "\n";

// Output the memory address of name (0x6dfed4)


cout << &name << "\n";

// Output the memory address of name with the pointer (0x6dfed4)


cout << ptr << "\n";

CODE:
using namespace std;
#include <iostream>
int main()

pg. 29
AL-JUNAID INSTITUTE of GROUP
{
string name="JUNAID MALIK";
string *ptr=&name;
cout<<"value in Variables :"<<name;
cout<<'\n';
cout<<"memory Adrres of name : "<<&name<<'\n';
cout<<"Address of Pointers : "<<ptr;

return 0;
}

Functions:
Functions are blocks of Code which are used to perform specific
Tasks.
In C++ a function needs to be declared before it is used.
Function Have a function Definition, function body and return type.
Function with return type not as void need to return a value at the end.
Function with return type void do not return any value.

SYNATX:
void myFunction() {
// code to be executed
}

CODE:
using namespace std;
#include <iostream>

pg. 30
AL-JUNAID INSTITUTE of GROUP
int add(int x ,int y){
return x+y;
}
int main()
{
cout<<add(5 ,10); //Now we want Value pass
return 0;
}

CODE No 2:
using namespace std;
#include <iostream>

void myfunction(){
cout<<"this is my Function";
}
int main(){
myfunction();
return 0;

pg. 31
AL-JUNAID INSTITUTE of GROUP
Function Overloading:
Function Overloading is the process of having two or
more functions with same name but different definition,
The Return Type, type of Parameters or the Number of Para Meters which the
Function takes must be different for function overloading to happen.

Int main()
{
Add(10.0,11.5);
Add(10,20);
}
Int add(int x, int y)
{
Return x+y;
}
Double add(double x,double y)
{

pg. 32
AL-JUNAID INSTITUTE of GROUP
Return x+y;
}

CODE:
using namespace std;
#include <iostream>

double add(double x,double y){


return x+y;
}
int add(int x,int y){
return x+y;
}
int main(){
cout<<"Adding of 1st Number :"<<add(3,4)<<'\n';
cout<<"Adding of 2nd Number :"<<add(3.45,4.98);
return 0;
}

CODE No 2:
// functionoverloading.cpp
#include <iostream>
using namespace std;
void display ( ) //function with no arguments

pg. 33
AL-JUNAID INSTITUTE of GROUP
{
int a = 3;
cout << a << endl;
}
void display (int a ) //function with one integer argument
{
cout << a << endl;
}
void display (double a ) //function with one floating argument
{
cout << a << endl;
}
void display(int a, float b) //function with one integer and one floating arguments
{
cout<< a << " , " << b << endl;
}

int main()
{
display(); //function call with no arguments
display(5); //function call with one integer argument
display(2.3); //function call with one floating argument
display(5,4.0); //function call with one integer and one floating arguments
return 0;
} //end of program

pg. 34
AL-JUNAID INSTITUTE of GROUP
CLASSES in C++:
C++ is an object oriented programming Language
supported classes. It is user define data type
Classes are a bundle of Attributes and Functions
Attributes are used for data storage and functions are used to process/works on that
data.
These are often referred to as “class members”.
Classes are user defined data type.
Objects:
Objects are the instances of class

CODE:
using namespace std;
#include <iostream>

class Student {
public:
int id;
string name;

//Details of Student dene kelie Get ka use kare ge

void get_details(){

pg. 35
AL-JUNAID INSTITUTE of GROUP
cout<<"id :"<<id;
cout<<'\n'<<"name :"<<name;
}
};
int main(){
//class ka ek instance bnana hoga
Student s1;
s1.id=1;
cout<<'\n';
s1.name="junaid";
s1.get_details();
}

CODE No 2:
Now We get Details from Students:
using namespace std;
#include <iostream>

class Student {
public:
int id;
string name; //if we want details from user then

void put_details(int i,string n){ //this is parameterise methood then


we assign data type

pg. 36
AL-JUNAID INSTITUTE of GROUP
id=i;
name=n;
}

//Details of Student dene kelie Get ka use kare ge

void get_details(){
cout<<"id :"<<id;
cout<<'\n'<<"name :"<<name;
}
};
int main(){
//class ka ek instance bnana hoga
Student s1;
int s_id;
string s_name;
cout<<"Enter Your Student ID: ";
cin>>s_id;
cout<<"Enter Your Name :";
cin>>s_name;
s1.put_details(s_id,s_name);
s1.get_details();
}

pg. 37
AL-JUNAID INSTITUTE of GROUP
CONSTRUCTORS:
Constructors are special function of a class which are
used to initializes the attributes of Class.
Constructors has two types:
1. Parameterized constructor
2. Non-Parameterized Constructor
EXAMPLE: of Constructor:
Class MyClass{
Public:
Int a,b;
MyClass(int x, int y) {a=x;b=y;}
void print(){
cout<<”a : “<<a<<” b : “<<b<<”\n”;
}
};

CODE:
using namespace std;
#include <iostream>

class MyClass{
public:
int a;
int b;

pg. 38
AL-JUNAID INSTITUTE of GROUP
MyClass(int x ,int y){a=x;b=y;}
void print(){
cout<<"a :"<<a<<'\n';
cout<<"b :"<<b<<'\n';
}
};
int main(){
//yaha par Constructor h then hum () ye use kre ge
//agar Constructor na ho then : use kar lo
MyClass m1 (10,20);

m1.print();
return 0;
}

Destructor:
C++ destructor is a special member function that is executed automatically when
an object is destroyed that has been created by the constructor. C++ destructors
are used to de-allocate the memory that has been allocated for the object by the
constructor.

SYNTAX:
/*...syntax of destructor....*/

class class_name

pg. 39
AL-JUNAID INSTITUTE of GROUP
public:

class_name(); //constructor.

~class_name(); //destructor.

CODE:
/*.....A program to highlight the concept of destructor.......... */
#include <iostream>
using namespace std;
class ABC
{
public:
ABC () //constructor defined
{
cout << "Hey I am in constructor" << endl;
}
~ABC() //destructor defined
{
cout << "Hey I am in destructor" << endl;
}
};

int main()
{

pg. 40
AL-JUNAID INSTITUTE of GROUP
ABC cc1; //constructor is called
cout << "function main is terminating" << endl;
/*....object cc1 goes out of scope ,now destructor is being called...*/
return 0;
} //end of program

Constructor Overloading
Likewise function overloading, a class can have more than one constructor. Since
more than one constructor is defined in a class it is called c++ constructor
overloading.

CODE:
/*.....A program to highlight the concept of constructor overloading.......... */
#include <iostream>
using namespace std;
class ABC
{
private:
int x,y;
public:
ABC () //constructor 1 with no arguments
{
x = y = 0;
}
ABC(int a) //constructor 2 with one argument

pg. 41
AL-JUNAID INSTITUTE of GROUP
{
x = y = a;
}
ABC(int a,int b) //constructor 3 with two argument
{
x = a;
y = b;
}
void display()
{
cout << "x = " << x << " and " << "y = " << y << endl;
}
};

int main()
{
ABC cc1; //constructor 1
ABC cc2(10); //constructor 2
ABC cc3(10,20); //constructor 3
cc1.display();
cc2.display();
cc3.display();
return 0;
} //end of program

pg. 42
AL-JUNAID INSTITUTE of GROUP
Inheritance:
Inheritance id termed as the incident when a class gains direct or
indirect access to other class’s attributes and properties.
The Class being inherited is known as based class and the class which inherits is
called sub class.
Subclass has access to public and protected members of the base class.

Types of Inheritance:
 Single Inheritance
 Multi Inheritance
 Hierarchical Inheritance
 Multilevel Inheritance
 Hybrid inheritance

1. Single Inheritance
Syntax:
Class Dimensions {
Public:
Float side=10.67;
};
Class Square: public Dimensions{
Public:
Double area (double x){
Return(x*x);
}
};
Int main(){

pg. 43
AL-JUNAID INSTITUTE of GROUP
Square s1;
Cout<<” Area; “<<s1.area(s1.side);
Return 0;
}

Another Syntax of Single Inheritance:

CODE:
// inheritance.cpp
#include <iostream>
using namespace std;
class base //single base class
{
public:
int x;
void getdata()

pg. 44
AL-JUNAID INSTITUTE of GROUP
{
cout << "Enter the value of x = "; cin >> x;
}
};
class derive : public base //single derived class
{
private:
int y;
public:
void readdata()
{
cout << "Enter the value of y = "; cin >> y;
}
void product()
{
cout << "Product = " << x * y;
}
};
int main()
{
derive a; //object of derived class
a.getdata();
a.readdata();
a.product();
return 0;

pg. 45
AL-JUNAID INSTITUTE of GROUP
} //end of program

Multilevel Inheritance:
If a class is derived from another derived class, then it is called multilevel
inheritance. So in C++ multilevel inheritance, a class has more than one parent
class.

SYNTAX:
class A // base class
{
...........
};
class B : acess_specifier A // derived class
{
...........

pg. 46
AL-JUNAID INSTITUTE of GROUP
};
class C : access_specifier B // derived from derived class B
{
...........
};

CODE:
// inheritance.cpp
#include <iostream>
using namespace std;
class base //single base class
{
public:
int x;
void getdata()
{
cout << "Enter value of x= "; cin >> x;
}
};
class derive1 : public base // derived class from base class
{
public:
int y;
void readdata()
{

pg. 47
AL-JUNAID INSTITUTE of GROUP
cout << "\nEnter value of y= "; cin >> y;
}
};
class derive2 : public derive1 // derived from class derive1
{
private:
int z;
public:
void indata()
{
cout << "\nEnter value of z= "; cin >> z;
}
void product()
{
cout << "\nProduct= " << x * y * z;
}
};
int main()
{
derive2 a; //object of derived class
a.getdata();
a.readdata();
a.indata();
a.product();
return 0;

pg. 48
AL-JUNAID INSTITUTE of GROUP
} //end of program

Hierarchical Inheritance:
When several classes are derived from common base class it is called hierarchical
inheritance.

SYNTAX:
class A // base class
{
..............
};
class B : access_specifier A // derived class from A
{
...........
};

pg. 49
AL-JUNAID INSTITUTE of GROUP
class C : access_specifier A // derived class from A
{
...........
};
class D : access_specifier A // derived class from A
{
...........
};

CODE:
// hierarchial inheritance.cpp
#include <iostream>
using namespace std;
class A //single base class
{
public:
int x, y;
void getdata()
{
cout << "\nEnter value of x and y:\n"; cin >> x >> y;
}
};
class B : public A //B is derived from class base
{
public:

pg. 50
AL-JUNAID INSTITUTE of GROUP
void product()
{
cout << "\nProduct= " << x * y;
}
};
class C : public A //C is also derived from class base
{
public:
void sum()
{
cout << "\nSum= " << x + y;
}
};
int main()
{
B obj1; //object of derived class B
C obj2; //object of derived class C
obj1.getdata();
obj1.product();
obj2.getdata();
obj2.sum();
return 0;
} //end of program

pg. 51
AL-JUNAID INSTITUTE of GROUP
Multiple Inheritance:
If a class is derived from two or more base classes, then it is called
multiple inheritance. In C++ multiple inheritance a derived class has
more than one base class.
How does multiple inheritance differ from multilevel inheritance?
Though but multiple and multilevel sounds like same but they differ hugely in
meaning. In multilevel inheritance, we have multiple parent classes whereas in in
multiple inheritance we have multiple base classes.

To put it in simple words, in multilevel inheritance, a class is derived from a class


which is also derived from another base class. And these levels of inheritance can
be extended. On the contrary, in multiple inheritance, a class is derived from two
different base classes.

For example

 Multilevel inheritance: Inheritance of characters by a child from father and


father inheriting characters from his father (grandfather)
 Multiple inheritance: Inheritance of characters by a child from mother and
father

pg. 52
AL-JUNAID INSTITUTE of GROUP
SYNTAX:
class A

..........

};

class B

...........

};

class C : acess_specifier A,access_specifier A // derived class from A and B

...........

};

CODE:
// multiple inheritance.cpp
#include <iostream>
using namespace std;
class A
{
public:

pg. 53
AL-JUNAID INSTITUTE of GROUP
int x;
void getx()
{
cout << "enter value of x: "; cin >> x;
}
};
class B
{
public:
int y;
void gety()
{
cout << "enter value of y: "; cin >> y;
}
};
class C : public A, public B //C is derived from class A and
class B
{
public:
void sum()
{
pg. 54
AL-JUNAID INSTITUTE of GROUP
cout << "Sum = " << x + y;
}
};
int main()
{
C obj1; //object of derived class C
obj1.getx();
obj1.gety();
obj1.sum();
return 0;
} //end of program

pg. 55
AL-JUNAID INSTITUTE of GROUP
Hybrid inheritance
The inheritance in which the derivation of a class involves more than one form of
any inheritance is called hybrid inheritance. Basically C++ hybrid inheritance is
combination of two or more types of inheritance. It can also be called multi path
inheritance.

Above block diagram shows the hybrid combination of single inheritance and
multiple inheritance. Hybrid inheritance is used in a situation where we need to apply
more than one inheritance in a program.

As in other inheritance, based on the visibility mode used or access specifier used
while deriving, the properties of the base class are derived. Access specifier can be
private, protected or public.

SYNTAX:
class A

.........

pg. 56
AL-JUNAID INSTITUTE of GROUP
};

class B : public A

..........

};

class C

...........

};

class D : public B, public C

...........

};

CODE:
// hybrid inheritance.cpp

#include <iostream>

using namespace std;

class A

pg. 57
AL-JUNAID INSTITUTE of GROUP
public:

int x;

};

class B : public A

public:

B() //constructor to initialize x in base class A

x = 10;

};

class C

public:

int y;

C() //constructor to initialize y

y = 4;

};

class D : public B, public C //D is derived from class B and class C

pg. 58
AL-JUNAID INSTITUTE of GROUP
{

public:

void sum()

cout << "Sum= " << x + y;

};

int main()

D obj1; //object of derived class D

obj1.sum();

return 0;

} //end of program

C++ Virtual Functions

A virtual function is a member function of the base class, that is overridden in


derived class. The classes that have virtual functions are called polymorphic classes.

The compiler binds virtual function at runtime, hence called runtime polymorphism.
Use of virtual function allows the program to decide at runtime which function is to
be called based on the type of the object pointed by the pointer.

In C++, the member function of a class is selected at runtime using virtual function.
The function in the base class is overridden by the function with the same name of
the derived class.

pg. 59
AL-JUNAID INSTITUTE of GROUP
C++ virtual function:
Syntax
Class class_name

public:

virtual return func_name( args.. )

//function definition

Why do we need virtual functions?


Virtual functions are needed for many reasons, among them to eliminate ambiguity
is one.

Let’s make it more clear with this example and know when and why we need to use
virtual functions.

CODE:
#include <iostream>

using namespace std;

class junaid

pg. 60
AL-JUNAID INSTITUTE of GROUP
public:

void my_features()

cout << "\n my name is Junaid.";

};

class ali : public junaid

public:

void my_features()

cout << "\n my name is Ali.";

};

class malik : public junaid

public:

void my_features()

cout << "\n my name is Malik.";

pg. 61
AL-JUNAID INSTITUTE of GROUP
};

int main()

junaid *obj1 = new junaid;

ali *obj2 = new ali;

malik *obj3 = new malik;

obj1->my_features();

obj2->my_features();

obj3->my_features();

return 0;

Everything going as we expected, right.


We created a three pointer objects *obj1, *obj2 and *obj3. And when we call
function my_features() using these pointer objects, the corresponding
functions of the classes are executed.

CODE:
#include <iostream>

using namespace std;

class junaid

public:

pg. 62
AL-JUNAID INSTITUTE of GROUP
void my_features()

cout << "\n my name is Junaid.";

};

class ali : public junaid

public:

void my_features()

cout << "\n my name is Ali.";

};

class malik : public junaid

public:

void my_features()

cout << "\n my name is Malik.";

pg. 63
AL-JUNAID INSTITUTE of GROUP
};

//intermediate function

void intermediate_func(junaid *a1)

a1->my_features();

int main()

junaid *obj1 = new junaid;

ali *obj2 = new ali;

malik *obj3 = new malik;

intermediate_func(obj1);

intermediate_func(obj2);

intermediate_func(obj3);

return 0;

Junaidfazal08@gmail.com
For More Visit:
http://vulmshelp.com/

pg. 64

You might also like