0% found this document useful (0 votes)
33 views57 pages

CPP Assigentment

C++ is a general-purpose, object-oriented programming language created in 1980. It is very similar to C and is compatible with 99% of C programs. C++ is widely used today in operating systems, user interfaces, and embedded systems due to its versatility. C++ supports object-oriented concepts like classes, inheritance, and polymorphism which make programs modular and reusable.

Uploaded by

fakemailb4k
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
33 views57 pages

CPP Assigentment

C++ is a general-purpose, object-oriented programming language created in 1980. It is very similar to C and is compatible with 99% of C programs. C++ is widely used today in operating systems, user interfaces, and embedded systems due to its versatility. C++ supports object-oriented concepts like classes, inheritance, and polymorphism which make programs modular and reusable.

Uploaded by

fakemailb4k
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 57

 What is C++?

C++ is a general-purpose, object-oriented programming language. It was created by


BjarneStroustrup at Bell Labs circa 1980. C++ is very similar to C (invented by Dennis
Ritchie in the early 1970s). C++ is so compatible with C that it will probably compile over
99% of C programs without changing a line of source code. Though C++ is a lot of well-
structured and safer language than C as it OOPs based.

Some computer languages are written for a specific purpose. Like, Java was initially
devised to control toasters and some other electronics. C was developed for
programming OS. Pascal was conceptualized to teach proper programming techniques.
But C++ is a general-purpose language. It well deserves the widely acknowledged
nickname “Swiss Pocket Knife of Languages.”

 Why Use C++?

 C++ is one of the world's most popular programming languages.

 C++ can be found in today's operating systems, Graphical User Interfaces, and

embedded systems.

 C++ is an object-oriented programming language which gives a clear structure to

programs and allows code to be reused, lowering development costs.

 C++ is portable and can be used to develop applications that can be adapted to

multiple platforms.

 C++ is fun and easy to learn!

 Features Of C++?

1
 OOPS Concept in C++?
The major purpose of C++ programming is to introduce the concept of object orientation
to the C programming language.

Object Oriented Programming is a paradigm that provides many concepts such


as inheritance, data binding, polymorphism etc.

The programming paradigm where everything is represented as an object is known as


truly object-oriented programming language. Smalltalk is considered as the first truly
object-oriented programming language.

Objectsimplifies the software development and maintenance by providing some


concepts:

 Object
 Class
 Inheritance
 Polymorphism
 Abstraction
 Encapsulation

Object
Any entity that has state and behavior is known as an object. For example: chair, pen,
table, keyboard, bike etc. It can be physical and logical.

Class
Collection of objects is called class. It is a logical entity.
#include <iostream>
#include <string>
using namespacestd;
classMyClass { // The class
public: // Access specifier
intmyNum; // Attribute (int variable)
stringmyString; // Attribute (string variable)

2
};
int main() {
MyClassmyObj; // Create an object of MyClass
// Access attributes and set values
myObj.myNum = 15;
myObj.myString = "Some text";
// Print values
cout<<myObj.myNum<<"\n";
cout<<myObj.myString;
return 0;
}
OUTPUT:

Inheritance
When one object acquires all the properties and behaviours of parent object i.e.
known as inheritance. It provides code reusability. It is used to achieve runtime
polymorphism.

Example:
#include <iostream>
using namespace std;
class Account {
public:
float salary = 60000;
};
class Programmer: public Account {
public:
float bonus = 5000;
};
int main(void) {
Programmer p1;
cout<<"Salary: "<<p1.salary<<endl;
cout<<"Bonus: "<<p1.bonus<<endl;
return 0;
}

OUTPUT:

3
Polymorphism
When one task is performed by different ways i.e. known as polymorphism. For
example: to convince the customer differently, to draw something e.g. shape or
rectangle etc.

In C++, we use Function overloading and Function overriding to achieve polymorphism.

Abstraction
Hiding internal details and showing functionality is known as abstraction. For
example: phone call, we don't know the internal processing.

In C++, we use abstract class and interface to achieve abstraction.

Exampl

#include <iostream>

using namespace std;


class Adder {
public:
// constructor
Adder(int i = 0) {
total = i;
}
// interface to outside world
void addNum(int number) {
total += number;
}
// interface to outside world
int getTotal() {
return total;
};
private:
// hidden data from outside world
int total;
};
int main() {
Adder a;
a.addNum(10);
a.addNum(20);
a.addNum(30);
cout << "Total " << a.getTotal() <<endl;
return 0;
}
OUTPUT:

4
Encapsulation
Binding (or wrapping) code and data together into a single unit is known as
encapsulation. For example: capsule, it is wrapped with different medicines.

Example:
#include<iostream>
using namespace std;
class Encapsulation
{
private:
// data hidden from outside world
int x;
public:
// function to set value of
// variable x
void set(int a)
{
x =a;
}
// function to return value of
// variable x
int get()
{
return x;
}
};
// main function
int main()
{
Encapsulation obj;
obj.set(5);
cout<<obj.get();
return 0;
}
OUTPUT:

 Loops in C++
In general, C++ programming language follows a sequential execution approach.
The first statement is executed and then the compiler moves to the next statement in
line. In case of a conditional statement, the statement is executed depending on the
result of the condition. In addition, you can use looping statements in C++ when you
want to repeat the execution of a specific block of code till a specific condition is

5
satisfied. For example, you want to print numbers from 1 to 10. Instead of manually
writing the code with 10 separate print statements, you can define a loop statement
and let the compiler to manually increment the value after every iteration and print
the value. You can finish writing this piece of code in just 2-3 lines.

The looping statements available in C++ are :


 For loop
 While loop
 Do .. While loop

For Loop
For loop can be used in C++ programming to repeat a specific execution for specific
number of times. This helps us to avoid writing multiple lines of code and bring
everything into a single line. The syntax of for loop is :

for (variable initialization; condition; increment operation)


{
//loop statements;
}

The initialization step allows you to declare and initialize a variable. In the next step,
you can evaluate the variable against a condition and in the final step, you can
increment or decrement the value of the variable. The loop will execute till the
condition becomes false. Then, the program will exit the loop and continue with the
rest of the statements.

Example:
#include <iostream>
using namespace std;

int main()
{
int a;
for (a=1; a<=10; a++)
{
cout << "The value of a is: " << a << '\n';
}
}

OUTPUT:

6
While Loop
While loop can be used when you want to a statement to execute continuously till
the condition specified is true. The difference between for loop and while loop is with
for loop, you will know how many times the loop will execute. With while loop, you
will not know the number of iterations till the program exits from the loop when the
condition does not match. The syntax of for loop is :

while (condition)
{
//loop statements;
}

Example:
#include <iostream>
using namespace std;

int main()
{
int a=1;
while (a<=10)
{
cout << "The value of a is: " << a << '\n';
a++;
}
}
OUTPUT:

Do .. While Loop
The basic difference between for loop, while loop and do while loop is that in do
while loop, the condition is checked at the bottom of the loop. In the do while loop,
the body of the loop will be executed first and then the condition will be evaluated.
This ensures that the statement is executed at least once even if the condition is not
satisfied. The syntax of do while loop is :

do
{
// statement execution;
}
while(condition);

7
Example:
#include <iostream>
using namespace std;

int main()
{
string a;
do
{
cout <<"Enter a word: " << '\n';
cin >> a;
cout << "You entered the word: " << a << '\n';
}
while (a != "bye");
}
OUTPUT:

2
Conditional structure: if then else
The ‘if’ statement allows you to execute an instruction or block of instructions only if the
specified condition is true. It has the following syntax:
if (condition) statement
If the statements to be executed in the
conditional structure are more than one
then the set of statements also referred
to as block of instructions to be
executed are enclosed in curly braces
({}).
if (condition)
{
block of instructions
}

Where ‘condition’ is the expression that is being evaluated. If this expression evaluates
to ‘true’, then the statement(s) are executed. On the other hand if the ‘condition’
provided in the ‘if’ statement evaluates to ‘false’, then the statement(s) are ignored and
the program jumps to the next instruction after the conditional structure.

8
This is where the ‘if…else’ structure comes in. It consists of the ‘if’ statement followed by
a set of instructions, followed by the keyword ‘else’, followed by another set of
instructions which is executed if the specified condition evaluates to false. The syntax for
the ‘if…else’ structure is given below:
Syntax;
if (condition)
{
// statements executed if specified condition is true statement(s);
}
else
{
// statements executed if the specified condition is false
statement(s);
}

For example,
Even or Odd:
#include <iostream>
usingnamespacestd;

intmain()
{
int num;
cout<<"Enter an integer number: ";
cin>>num;

if(num%2==0)
cout<<num<<" is an EVEN number."<<endl;
else
cout<<num<<" is an ODD number."<<endl;

return0;
}

Output

First run:
Enter an integer number: 10
10 is an EVEN number.

Second run:
Enter an integer number: 11
11 is an ODD number.

3 Repetitive structures or loops


Loops allow us to repeat instructions or a block of instructions while the specified
condition to initiate the loop remains true. Loops have an objective to repeat a

9
statement (or a set of statements) a certain number of times or till the moment the
required condition is fulfilled.
1 The while loop.
The while loop, is one of the most commonly used loops in most programming
language. This loop is generally used when we are not sure how many number of times
do we want to execute a loop. It has the following syntax:
Syntax:
while (expression)
{
statement(s)
}
2 The do-while loop.
The do-while loop as the name suggests is similar to the while loop. As we have already
studied in the while loop the condition or the text expression is evaluated at the starting
of the loop. If this expression evaluates to false then the program statements are not
executed at all but in some cases we actually might want to execute a set of instructions
at least once. This is made possible with the help of the do-while loop. It has the
following syntax:
Syntax:
do
{
Statement
}
while (condition);
3 The for loop.
The for loop executes a given section of code a given number of times. A for loop is
generally used when it is previously known from before how many times a loop has to
be executed. To be truthful the ‘for’ loop works exactly like the ‘while’ loop having space
for variable initialization and incrementation in its expression. It has the following syntax:
Syntax:
for (initialization; condition; increment)
{
statement(s);
}
3. Prime number
A prime number is a natural number that has only one and itself as factors. This C++
program used to demonstrates how to find out whether a natural number is prime or
not.

Example:

#include<iostream>
using namespace std;

int main()
{
/* variable definition and initialization */
int n,i, c =0;

/* Get user input */


cout<<"Enter any number n: ";cin>>n;

10
/*logic*/
for(i=1;i<= n;i++)
{
if(n %i==0)
{
c++;
}
}
if(c ==2)
{
cout<<"n is a Prime number"<<endl;
}
else
{
cout<<"n is not a Prime number"<<endl;
}
return 0;
}
Output:

4. Pattern
i. Program to print full pyramid using

*
* * *
* * * * *
* * * * * * *
* * * * * * * * *

Code

#include<iostream>
using namespace std;

11
int main()
{
int space, rows;

cout<<"Enter number of rows: ";


cin>> rows;

for(inti = 1, k = 0; i<= rows; ++i, k = 0)


{
for(space = 1; space <= rows-i; ++space)
{
cout<<" ";
}

while(k != 2*i-1)
{
cout<<"* ";
++k;
}
cout<<endl;
}
return 0;
}

ii. Program to print half pyramid a using numbers


1
12
123
1234
12345
Code
#include<iostream>
using namespace std;

int main()
{
int rows;

cout<<"Enter number of rows: ";


cin>> rows;

for(inti = 1; i<= rows; ++i)


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

12
cout<< j <<" ";
}
cout<<"\n";
}
return 0;
}

5. Fibonacci series
The Fibonacci sequence is a series where the next term is the sum of the previous two
terms. The first two terms of the Fibonacci sequence is 0 followed by 1.
#include<iostream>

using namespace std;

int main(){

int n, t1 = 0, t2 = 1, nextTerm = 0;

cout<<"Enter the number of terms: ";

cin>> n;

cout<<"Fibonacci Series: ";

for (inti = 1; i<= n; ++i) {

// Prints the first two terms.

if(i == 1) {

cout<< t1 <<", ";

continue;

if(i == 2) {

13
cout<< t2 <<", ";

continue;

nextTerm = t1 + t2;

t1 = t2;

t2 = nextTerm;

cout<<nextTerm<<", ";

return0;

Output:

Enter the number of terms: 10

Fibonacci Series: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34,

6. Factorial Number
Factorial of a non-negative integer n is the product of all the positive integers that are less than
or equal to n.

For example: The factorial of 4 is 24.


4! = 4 * 3 * 2 *1
4! = 24

#include<iostream>
using namespace std;

int main(){
int n;

14
long factorial = 1.0;

cout<<"Enter a positive integer: ";


cin>> n;

if (n <0)
cout<<"Error! Factorial of a negative number doesn't exist.";
else {
for(inti = 1; i<= n; ++i) {
factorial *= i;
}
cout<<"Factorial of "<< n <<" = "<< factorial;
}

return 0;
}

Output:

Enter a positive integer: 4

Factorial of 4 = 24

7. Two Dimensional array

A Two Dimensional Array in C++ is a collection of 1D Array. It consists of rows and


columns and looks like a table. A 2D array is also known as Matrix.
Declaration Syntax of a Two Dimensional Array in C++

datatype variable_name[row_size][column_size];

Here row_size is the number of rows we want to create in a 2D array


and, column_size is the number of columns in each row.
include<iostream>
using namespace std;

int main(){
int numbers[2][3];

cout<<"Enter 6 numbers: "<<endl;

15
// Storing user input in the array
for (inti = 0; i<2; ++i) {
for (int j = 0; j <3; ++j) {
cin>> numbers[i][j];
}
}

cout<<"The numbers are: "<<endl;

// Printing array elements


for (inti = 0; i<2; ++i) {
for (int j = 0; j <3; ++j) {
cout<<"numbers["<<i<<"]["<< j <<"]: "<< numbers[i][j] <<endl;
}
}

return 0;
}

Output
Enter 6 numbers:

The numbers are:

numbers[0][0]: 1

16
numbers[0][1]: 2

numbers[0][2]: 3

numbers[1][0]: 4

numbers[1][1]: 5

numbers[1][2]: 6
8.Linear Search in C++

To search any element present inside the array in C++ programming using linear search
technique, you have to ask from user to enter any 10 numbers as 10 array elements and
then ask to enter a number to search as shown in the program given below.

This program doesn't allows user to define the size of an array. Later on, you will go
through the program that allows user to define the size and also prints all the indexes of
an element, if found multiple times.

This is the simplest program to implement linear search in C++.

#include<iostream>
using namespacestd;
int main()
{
intarr[10], i, num, index;
cout<<"Enter 10 Numbers: ";
for(i=0; i<10; i++)
cin>>arr[i];
cout<<"\nEnter a Number to Search: ";
cin>>num;
for(i=0; i<10; i++)
{
if(arr[i]==num)
{
index = i;
break;

17
}
}
cout<<"\nFound at Index No."<<index;
cout<<endl;
return 0;
}

Output:

9. Binary search
To search an element from an array using binary search technique in C++ programming,
you have to ask from user to enter any 10 elements for the array and then enter the
element or number to be search.

After searching the element using binary search technique, if it is available in the list,
then display the position of the element. Following C++ program asks from user to
enter any 10 array elements and an element to be search. Here is the simple binary
search program:

#include<iostream>
using namespace std;
int main()
{
int i, arr[10], num, first, last, middle;
cout<<"Enter 10 Elements (in ascending order): ";
for(i=0; i<10; i++)

18
cin>>arr[i];
cout<<"\nEnter Element to be Search: ";
cin>>num;
first = 0;
last = 9;
middle = (first+last)/2;
while(first <= last)
{
if(arr[middle]<num)
first = middle+1;
else if(arr[middle]==num)
{
cout<<"\nThe number, "<<num<<" found at Position "<<middle+1;
break;
}
else
last = middle-1;
middle = (first+last)/2;
}
if(first>last)
cout<<"\nThe number, "<<num<<" is not found in given Array";
cout<<endl;
return 0;
}
Output:

10. Bubble sort

19
To sort an array in ascending order using bubble sort in C++ programming, you have to
ask from user to enter the array size and its elements. Now start sorting the array
elements using the bubble sort technique and display the sorted array on the screen as
shown here in the following program.

#include<iostream>
using namespacestd;
int main()
{
int n, i, arr[50], j, temp;
cout<<"Enter the Size (max. 50): ";
cin>>n;
cout<<"Enter "<<n<<" Numbers: ";
for(i=0; i<n; i++)
cin>>arr[i];
cout<<"\nSorting the Array using Bubble Sort Technique..\n";
for(i=0; i<(n-1); i++)
{
for(j=0; j<(n-i-1); j++)
{
if(arr[j]>arr[j+1])
{
temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
cout<<"\nArray Sorted Successfully!\n";
cout<<"\nThe New Array is: \n";
for(i=0; i<n; i++)
cout<<arr[i]<<" ";
cout<<endl;
return 0;
}

Output:

20
11. Leap Year in C++

To check whether the input year is a leap year or not in C++ programming, you have to
ask from user to enter the year first and then apply the logic and print the message as
shown in the program given below:

So the question is, write a program in C++ to check whether a year is a leap year or
not. The answer to this question is given below:

#include<iostream>
using namespacestd;
int main()
{
intyr;
cout<<"Enter the Year: ";
cin>>yr;
if((yr%4==0) && (yr%100!=0))
cout<<"\nIt is a Leap Year";
else if(yr%400==0)
cout<<"\nIt is a Leap Year";
else
cout<<"\nIt is not a Leap Year";
cout<<endl;
return 0;
}
Output:

12. Constructor

21
In C++, constructor is a special method which is invoked automatically at the time of
object creation. It is used to initialize the data members of new object generally. The
constructor in C++ has the same name as class or structure.

Constructor does not have a return value, hence they do not have a return type.
The prototype of Constructors is as follows:

<class-name> (list-of-parameters);

Constructors can be defined inside or outside the class declaration:-


The syntax for defining the constructor within the class:

<class-name> (list-of-parameters) { // constructor definition }

The syntax for defining the constructor outside the class:

<class-name>: :<class-name> (list-of-parameters){ // constructor definition}

There can be three types of constructors in C++.

o Default constructor
o Parameterized constructor
o Copy constructor

i. C++ Default Constructor


Default constructor is also known as a zero-argument constructor, as it doesn’t take

any parameter. It can be defined by the user if not then the compiler creates it on his

own. Default constructor always initializes data members of the class with the same

value they were defined.

Syntax:

class class_name{

private:

22
// private members

public:

// declaring default constructor

class_name()

// constructor body}

};

// C++ program to demonstrate the use of default constructor

#include<iostream>
using namespace std;

// declare a class
class Wall {
private:
double length;

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;
}

23
Output

Creating a Wall

Length = 5.5
ii. C++ Parameterized Constructor
Parameterized constructor is used to initialize data members with the values provided

by the user. This constructor is basically the upgraded version of the default

constructor. We can define more than one parameterized constructor according to the

need of the user, but we have to follow the rules of the function overloading, like a

different set of arguments must be there for each constructor.

Syntax:

classclass_name{
private:
// private members
public:
// declaring parameterized constructor
class_name(parameter1, parameter2,...)
{
// constructor body
}
};

// C++ program to calculate the area of a wall

#include<iostream>
using namespace std;

// declare a class
class Wall {
private:
double length;
double height;

public:
// parameterized constructor to initialize variables

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

double calculateArea(){
return length * height;
}
};

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;
}

Output

Area of Wall 1: 90.3

Area of Wall 2: 53.55

iii. C++ Copy Constructor


If we have an object of a class and we want to create its copy in a new declared

object of the same class, then a copy constructor is used. The compiler provides

each class a default copy constructor and users can define it also. It takes a single

argument which is an object of the same class.

Syntax:

class class_name{

25
private:

// private members

public:

// declaring copy constructor

class_name(constclass_name& obj)

// constructor body

};

#include<iostream>
using namespace std;

// declare a class
class Wall {
private:
double length;
double height;

public:

// initialize variables with parameterized constructor


Wall(double len, double hgt) {

26
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;
}

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;

// print areas of wall1 and wall2


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

return 0;
}

Output:

Area of Wall 1: 90.3

Area of Wall 2: 90.3

13. Destructor
Destructor is an instance member function which is invoked automatically whenever an
object is going to be destroyed. Meaning, a destructor is the last function that is going
to be called before an object is destroyed.
 Destructor is also a special member function like constructor. Destructor
destroys the class objects created by constructor.

27
 Destructor has the same name as their class name preceded by a tilde (~)
symbol.
 It is not possible to define more than one destructor.
 The destructor is only one way to destroy the object create by constructor.
Hence destructor can-not be overloaded.
 Destructor neither requires any argument nor returns any value.
 It is automatically called when object goes out of scope.
 Destructor release memory space occupied by the objects created by
constructor.
 In destructor, objects are destroyed in the reverse of an object creation.

The thing is to be noted here, if the object is created by using new or the constructor
uses new to allocate memory which resides in the heap memory or the free store, the
destructor should use delete to free the memory.
Syntax:
Syntax for defining the destructor within the class
~ <class-name>()
{

Syntax for defining the destructor outside the class


<class-name>: : ~ <class-name>()
{

Example:

#include <iostream>
using namespace std;
class Test
{

28
public:
Test()
{
cout<<"Test Object Created"<<endl;
}
~Test()
{
cout<<"Test Object Destroyed"<<endl;
}
};
int main()
{
Test *obj = newTest();
delete obj;
return 0;
}
Output:

14. Inheritance

In C++, inheritance is a process in which one object acquires all the properties and
behaviors of its parent object automatically. In such way, you can reuse, extend or
modify the attributes and behaviors which are defined in other class.

In C++, the class which inherits the members of another class is called derived class and
the class whose members are inherited is called base class. The derived class is the
specialized class for the base class.

Types Of Inheritance

o Single inheritance
o Multiple inheritance

29
o Hierarchical inheritance
o Multilevel inheritance
o Hybrid inheritance

Derived Classes

A Derived class is defined as the class derived from the base class.

The Syntax of Derived class:

class derived_class_name :: visibility-mode base_class_name


{
// body of the derived class.
}

Where,

derived_class_name: It is the name of the derived class.

visibility mode: The visibility mode specifies whether the features of the base class are
publicly inherited or privately inherited. It can be public or private.

base_class_name: It is the name of the base class.

30
o When the base class is privately inherited by the derived class, public members of the
base class becomes the private members of the derived class. Therefore, the public
members of the base class are not accessible by the objects of the derived class only by
the member functions of the derived class.
o When the base class is publicly inherited by the derived class, public members of the
base class also become the public members of the derived class. Therefore, the public
members of the base class are accessible by the objects of the derived class as well as by
the member functions of the base class.

i. C++ Single Inheritance

Single inheritance is defined as the inheritance in which a derived class is inherited


from the only one base class.

Where 'A' is the base class, and 'B' is the derived class.

Single Level Inheritance Example:

When one class inherits another class, it is known as single level inheritance. Let's see
the example of single level inheritance which inherits the fields only.

#include <iostream>
using namespace std;
class Account {
public:
float salary = 60000;
};
class Programmer: public Account {
public:
float bonus = 5000;
};
int main(void) {
Programmer p1;
cout<<"Salary: "<<p1.salary<<endl;
cout<<"Bonus: "<<p1.bonus<<endl;

31
return 0;
}

Output:

Salary: 60000
Bonus: 5000

In the above example, Employee is the base class and Programmer is the derived class.

ii.C++ Multilevel Inheritance

Multilevel inheritance is a process of deriving a class from another derived class.

C++ Multi Level Inheritance Example

When one class inherits another class which is further inherited by another class, it is
known as multi level inheritance in C++. Inheritance is transitive so the last derived class
acquires all the members of all its base classes.

#include <iostream>
using namespace std;
class Animal {
public:
void eat() {
cout<<"Eating..."<<endl;
}
};
class Dog: public Animal
{
public:
void bark(){
cout<<"Barking..."<<endl;
}
};
class BabyDog: public Dog

32
{
public:
void weep() {
cout<<"Weeping...";
}
};
int main(void) {
BabyDog d1;
d1.eat();
d1.bark();
d1.weep();
return 0;
}

Output:

Eating...
Barking...
Weeping...

iii. C++ Multiple Inheritance

Multiple inheritance is the process of deriving a new class that inherits the attributes
from two or more classes.

Example:
#include <iostream>
using namespace std;
class A
{
protected:
int a;
public:
void get_a(int n)
{
a = n;

33
}
};

class B
{
protected:
int b;
public:
void get_b(int n)
{
b = n;
}
};
class C : public A,public B
{
public:
void display()
{
std::cout << "The value of a is : " <<a<< std::endl;
std::cout << "The value of b is : " <<b<< std::endl;
cout<<"Addition of a and b is : "<<a+b;
}
};
int main()
{
C c;
c.get_a(10);
c.get_b(20);
c.display();
return 0;
}
Output:
The value of a is : 10
The value of b is : 20

34
Addition of a and b is : 30

In the above example, class 'C' inherits two base classes 'A' and 'B' in a public mode.

iv. C++ Hybrid Inheritance

Hybrid inheritance is a combination of more than one type of inheritance.

Example:
#include <iostream>
using namespace std;
class A
{
protected:
int a;
public:
void get_a()
{
std::cout << "Enter the value of 'a' : " << std::endl;
cin>>a;
}
};

class B : public A
{
protected:
int b;
public:
void get_b()
{
std::cout << "Enter the value of 'b' : " << std::endl;
cin>>b;
}
};
class C

35
{
protected:
int c;
public:
void get_c()
{
std::cout << "Enter the value of c is : " << std::endl;
cin>>c;
}
};

class D : public B, public C


{
protected:
int d;
public:
void mul()
{
get_a();
get_b();
get_c();
std::cout << "Multiplication of a,b,c is : " <<a*b*c<< std::endl;
}
};
int main()
{
D d;
d.mul();
return 0;
}

Output:

Enter the value of 'a' :


10

36
Enter the value of 'b' :
20
Enter the value of c is :
30
Multiplication of a,b,c is : 6000

v. C++ Hierarchical Inheritance

Hierarchical inheritance is defined as the process of deriving more than one class from a
base class.

Example:
#include <iostream>
using namespace std;
class Shape // Declaration of base class.
{
public:
int a;
int b;
void get_data(int n,int m)
{
a= n;
b = m;
}
};
class Rectangle : public Shape // inheriting Shape class
{
public:
intrect_area
{
int result = a*b;
return result;
}
};
class Triangle : public Shape // inheriting Shape class

37
{
public:
int triangle_area()
{
float result = 0.5*a*b;
return result;
}
};
int main()
{
Rectangle r;
Triangle t;
int length,breadth,base,height;
std::cout << "Enter the length and breadth of a rectangle: " << std::endl;
cin>>length>>breadth;
r.get_data(length,breadth);
int m = r.rect_area();
std::cout << "Area of the rectangle is : " <<m<< std::endl;
std::cout << "Enter the base and height of the triangle: " << std::endl;
cin>>base>>height;
t.get_data(base,height);
float n = t.triangle_area();
std::cout <<"Area of the triangle is : " << n<<std::endl;
return 0;
}

Output:

Enter the length and breadth of a rectangle:


23
20
Area of the rectangle is : 460
Enter the base and height of the triangle:
2
5
Area of the triangle is : 5

38
15. Pointers
Pointers are symbolic representations of addresses. They enable programs to simulate
call-by-reference as well as to create and manipulate dynamic data structures. Iterating
over elements in arrays or other data structures is one of the main use of pointers.
The address of the variable you’re working with is assigned to the pointer variable that
points to the same data type (such as an int or string).
Syntax:

datatype *var_name;
int *ptr; // ptr can point to an address which holds int data

Usage of pointer

1) Dynamic memory allocation

In c language, we can dynamically allocate memory using malloc() and calloc() functions
where pointer is used.

2) Arrays, Functions and Structures

Pointers in c language are widely used in arrays, functions and structures. It reduces the
code and improves the performance.

* C++ Pointers - Example Program of C++ Pointers */

#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int num=20;
int val;
int *iptr;

iptr = &num;
val = *iptr;

39
cout<<"Statements:\n";
cout<<"\tint num=20;\n\tint val;\n\tint *ptr;";
cout<<"\n\tiptr = &num;\n\tval = *iptr\n\n";
cout<<"Output:\n";
cout<<"\tnum = "<<num<<"\n\tval = "<<val;

getch();
}

Output:

16. Template
A template is a simple yet very powerful tool in C++. The simple idea is to pass data
type as a parameter so that we don’t need to write the same code for different data
types. For example, a software company may need to sort() for different data types.
Rather than writing and maintaining multiple codes, we can write one sort() and pass
data type as a parameter C++ adds two new keywords to support
templates: ‘template’ and ‘typename’. The second keyword can always be replaced by
the keyword class ;
Templates are expanded at compiler time. This is like macros. The difference is, that
the compiler does type checking before template expansion. The idea is simple, source
code contains only function/class, but compiled code may contain multiple copies of
the same function/class.

40
Function Templates : We write a generic function that can be used for different data
types. Examples of function templates are sort(), max(), min(), printArray().

Example :
// C++ program to demonstrate the use of class templates

#include<iostream>
usingn namespace std;

// Class template
template<classT>
classNumber {
private:
// Variable of type T
T num;

public:
Number(T n) : num(n) {} // constructor

41
T getNum(){
return num;
}
};

Int main(){

// create object with int type


Number<int>numberInt(7);

// create object with double type


Number<double>numberDouble(7.7);

cout<<"int Number = "<<numberInt.getNum() <<endl;


cout<<"double Number = "<<numberDouble.getNum() <<endl;

return 0;
}

Output

int Number = 7
double Number = 7.7

17. Virtual Function


A virtual function is a member function which is declared within a base class and is
re-defined (overridden) by a derived class. When you refer to a derived class object
using a pointer or a reference to the base class, you can call a virtual function for that
object and execute the derived class’s version of the function.

 Virtual functions ensure that the correct function is called for an object,
regardless of the type of reference (or pointer) used for function call.

 They are mainly used to achieve Runtime polymorphism

 Functions are declared with a virtual keyword in base class.

 The resolving of function call is done at runtime.

Rules for Virtual Functions

42
1. Virtual functions cannot be static.

2. A virtual function can be a friend function of another class.

3. Virtual functions should be accessed using pointer or reference of base class type
to achieve runtime polymorphism.

4. The prototype of virtual functions should be the same in the base as well as
derived class.

5. They are always defined in the base class and overridden in a derived class. It is
not mandatory for the derived class to override (or re-define the virtual function),
in that case, the base class version of the function is used.

6. A class may have virtual destructor but it cannot have a virtual constructor.

Compile time (early binding) VS runtime (late binding) behavior of Virtual


Functions

Consider the following simple program showing runtime behavior of virtual functions.

#include<iostream>
usingn namespace std;

class base {
public:
virtual void print()
{
cout << "print base class\n";
}

void show()
{
cout << "show base class\n";
}
};

class derived : public base {


public:
void print()
{

43
cout << "print derived class\n";
}

void show()
{
cout << "show derived class\n";
}
};

int main()
{
base *bptr;
derived d;
bptr = &d;

// Virtual function, binded at runtime


bptr->print();

// Non-virtual function, binded at compile time


bptr->show();

return 0;
}

Output

print derived class


show base class

18. ‘this’ Pointer

To understand ‘this’ pointer, it is important to know how objects look at functions


and data members of a class.

1. Each object gets its own copy of the data member.

2. All-access the same function definition as present in the code segment.

Meaning each object gets its own copy of data members and all objects share a
single copy of member functions.

44
Then now question is that if only one copy of each member function exists and is
used by multiple objects, how are the proper data members are accessed and
updated?

The compiler supplies an implicit pointer along with the names of the functions as
‘this’.

The ‘this’ pointer is passed as a hidden argument to all nonstatic member function
calls and is available as a local variable within the body of all nonstatic functions.
‘this’ pointer is not available in static member functions as static member functions
can be called without any object (with class name).

For a class X, the type of this pointer is ‘X* ‘. Also, if a member function of X is
declared as const, then the type of this pointer is ‘const X *’ (see this GFact)

In the early version of C++ would let ‘this’ pointer to be changed; by doing so a
programmer could change which object a method was working on. This feature was
eventually removed, and now this in C++ is an r-value.

C++ lets object destroy themselves by calling the following code :

delete this;

Following are the situations where ‘this’ pointer is used:

1) When local variable’s name is same as member’s name

#include<iostream>
using namespace std;

/* local variable is same as a member's name */


class Test
{
private:
int x;
public:
void setX (int x)
{
// The 'this' pointer is used to retrieve the object's x

45
// hidden by the local variable 'x'
this->x = x;
}
void print() { cout << "x = " << x << endl; }
};

int main()
{
Test obj;
int x = 20;
obj.setX(x);
obj.print();
return 0;
}

Output

x = 20

2) To return reference to the calling object

/* Reference to the calling object can be returned */


Test& Test::func ()
{
// Some processing
return *this;
}
19. Exception Handling

One of the advantages of C++ over C is Exception Handling. Exceptions are runtime
anomalies or abnormal conditions that a program encounters during its execution.
There are two types of exceptions: a)Synchronous, b)Asynchronous (i.e., exceptions
which are beyond the program’s control, such as disc failure, keyboard interrupts
etc.). C++ provides the following specialized keywords for this purpose:
try: Represents a block of code that can throw an exception.
catch: Represents a block of code that is executed when a particular exception is
thrown.
throw: Used to throw an exception. Also used to list the exceptions that a function
throws but doesn’t handle itself.

46
The following are the main advantages of exception handling over traditional error
handling:

1) Separation of Error Handling code from Normal Code: In traditional error handling
codes, there are always if-else conditions to handle errors. These conditions and the
code to handle errors get mixed up with the normal flow. This makes the code less
readable and maintainable. With try/catch blocks, the code for error handling
becomes separate from the normal flow.

2) Functions/Methods can handle only the exceptions they choose: A function can
throw many exceptions, but may choose to handle some of them. The other
exceptions, which are thrown but not caught, can be handled by the caller. If the
caller chooses not to catch them, then the exceptions are handled by the caller of
the caller.
In C++, a function can specify the exceptions that it throws using the throw keyword.
The caller of this function must handle the exception in some way (either by
specifying it again or catching it).

C++ try and catch:

Exception handling in C++ consists of three keywords: try, throw and catch:

The try statement allows you to define a block of code to be tested for errors while it is
being executed.

The throw keyword throws an exception when a problem is detected, which lets us
create a custom error.

The catch statement allows you to define a block of code to be executed if an error
occurs in the try block.

The try and catch keywords come in pairs:

We use the try block to test some code: If the value of a variable “age” is less than 18,
we will throw an exception, and handle it in our catch block.

In the catch block, we catch the error if it occurs and do something about it. The catch
statement takes a single parameter. So, if the value of age is 15 and that’s why we are
throwing an exception of type int in the try block (age), we can pass “int myNum” as the
parameter to the catch statement, where the variable “myNum” is used to output the
value of age.

47
If no error occurs (e.g. if age is 20 instead of 15, meaning it will be greater than 18), the
catch block is skipped.

Exception Handling in C++

1) The following is a simple example to show exception handling in C++. The output of
the program explains the flow of execution of try/catch blocks.

#include <iostream>
using namespace std;

int main()
{
int x = -1;

// Some code
cout << "Before try \n";
try {
cout << "Inside try \n";
if (x < 0)
{
throw x;
cout << "After throw (Never executed) \n";
}
}
catch (int x ) {
cout << "Exception Caught \n";
}

cout << "After catch (Will be executed) \n";


return 0;
}

Output

Before try
Inside try
Exception Caught
After catch (Will be executed)

48
2) There is a special catch block called the ‘catch all’ block, written as catch(…), that can
be used to catch all types of exceptions. For example, in the following program, an int is
thrown as an exception, but there is no catch block for int, so the catch(…) block will be
executed.

#include <iostream>
using namespace std;

int main()
{
try {
throw 10;
}
catch (char *excp) {
cout << "Caught " << excp;
}
catch (...) {
cout << "Default Exception\n";
}
return 0;
}

Output

Default Exception

20. Static data members

Static data members are class members that are declared using static keywords. A static
member has certain special characteristics. These are:

 Only one copy of that member is created for the entire class and is shared by all
the objects of that class, no matter how many objects are created.

 It is initialized before any object of this class is being created, even before main
starts.

 It is visible only within the class, but its lifetime is the entire program

Syntax

49
static data_type data_member_name;

#include <iostream>
using namespace std;

class A
{
public:
A() { cout << "A's Constructor Called " << endl; }
};

class B
{
static A a;
public:
B() { cout << "B's Constructor Called " << endl; }
};

int main()
{
B b;
return 0;
}

Output

B's Constructor Called

21. Array Pointer

Pointer to Array

Consider the following program:

#include <iostream>
using namespace std;

int main()
{
int arr[5] = { 1, 2, 3, 4, 5 };

50
int *ptr = arr;

cout <<"\n"<< ptr;


return 0;
}

In this program, we have a pointer ptr that points to the 0th element of the array.
Similarly, we can also declare a pointer that can point to whole array instead of only one
element of the array. This pointer is useful when talking about multidimensional arrays.
Syntax:

data_type (*var_name)[size_of_array];

Example:

int (*ptr)[10];

Here ptr is pointer that can point to an array of 10 integers. Since subscript have higher
precedence than indirection, it is necessary to enclose the indirection operator and
pointer name inside parentheses. Here the type of ptr is ‘pointer to an array of 10
integers’.
Note : The pointer that points to the 0 th element of array and the pointer that points to
the whole array are totally different. The following program shows this:

#include <iostream>
using namespace std;
int main()
{
// Pointer to an integer
int *p;

// Pointer to an array of 5 integers


int (*ptr)[5];
int arr[5];

// Points to 0th element of the arr.


p = arr;

51
// Points to the whole array arr.
ptr = &arr;

cout << "p =" << p <<", ptr = "<< ptr<< endl;
p++;
ptr++;
cout << "p =" << p <<", ptr = "<< ptr<< endl;

return 0;
}

Output

p = 0x7fff4f32fd50, ptr = 0x7fff4f32fd50


p = 0x7fff4f32fd54, ptr = 0x7fff4f32fd64

p: is pointer to 0th element of the array arr, while ptr is a pointer that points to the whole
array arr.

22. Friend Function

Like a friend class, a friend function can be granted special access to private and
protected members of a class in C++. They are the non-member functions that can
access and manipulate the private and protected members of the class for they are
declared as friends.

A friend function can be:

1. A global function

2. A member function of another class

Syntax:

friend return_type function_name (arguments); // for a global function


or
friend return_type class_name::function_name (arguments); // for a member function of
another class

52
1. Global Function as Friend Function

We can declare any global function as a friend function. The following example
demonstrates how to declare a global function as a friend function in C++:

Example:

#include <iostream>
using namespace std;

class base {
private:
int private_variable;

protected:
int protected_variable;

public:
base()
{
private_variable = 10;
protected_variable = 99;
}

// friend function declaration


friend void friendFunction(base& obj);
};

// friend function definition


void friendFunction(base& obj)
{
cout << "Private Variable: " << obj.private_variable
<< endl;
cout << "Protected Variable: " << obj.protected_variable;
}

// driver code
int main()
{
base object1;

53
friendFunction(object1);

return 0;
}

Output

Private Variable: 10
Protected Variable: 99

In the above example, we have used a global function as a friend function. In the next
example, we will use a member function of another class as a friend function.

2. Member Function of Another Class as Friend Function

We can also declare a member function of another class as a friend function in C++. The
following example demonstrates how to use a member function of another class as a
friend function in C++:

Example:

#include <iostream>
using namespace std;

class base; // forward definition needed


// another class in which function is declared
class anotherClass {
public:
void memberFunction(base& obj);
};

// base class for which friend is declared


class base {
private:
int private_variable;

protected:
int protected_variable;

54
public:
base()
{
private_variable = 10;
protected_variable = 99;
}

// friend function declaration


friend void anotherClass::memberFunction(base&);
};

// friend function definition


void anotherClass::memberFunction(base& obj)
{
cout << "Private Variable: " << obj.private_variable
<< endl;
cout << "Protected Variable: " << obj.protected_variable;
}

// driver code
int main()
{
base object1;
anotherClass object2;
object2.memberFunction(object1);

return 0;
}

Output

Private Variable: 10
Protected Variable: 99

55
CONCLUSION

C++ is a powerful programming language use that has been


used to develop a wide range of applications, from operating
system and compilers to video games and financial software.
It is a compiled language, which means that the code written
in C++ is translated into machine code by a compiler before it
is executed. This gives C++ programs high performance and
efficient memory management.

One of the key features of C++ is its support for objectoriented


programming (OOP), which allows developers to organize code
into reusable classes and objects. This makes it easier to write
complex programs and maintain them over
time. C++ also supports generic programming through
templates, which allow developers to write code that works
with different data types.

Another important feature of C++ is its extensive standard


library, which provides a wide range of functions and classes
for performing common tasks. This includes support for
input/output operations, string handling, mathematical
functions, and much more. Additionally, C++ supports thirdparty
libraries, which can be easily integrated into projects to add
additional functionality.

56
57

You might also like