C++ Module-1 Notes K
C++ Module-1 Notes K
DIGITAL NOTES
B.E.
(I YEAR – II SEM)
(2023-24)
DEPARTMENT OF CSE
BTI
Overview of C++ language:
1. C++ can be considered as an incremental version of c language which consists
all programming language constructs with newly added features of object oriented
programming.
2. c++ is structure(procedure) oriented and object oriented
programming language. 3.The file extension of C++ program is
“.CPP”
4. Function overloading and operator overloading are possible.
5. Variables can be declared in inline i.e when required
6. In c++ more emphasis is give on data rather than procedures
7. Polymorphism, encapsulation and inheritance are possible.
8. Data abstraction property is supported by c++.
9. Data access is limited. It can be accessed by providing various visibility
modes both for data and member functions. there by providing data security by
data hiding
10. Dymanic binding is
supported by C++ 11..It
supports all features of c
language
12. It can be called as an incremental version of c language
Difference Between Procedure Oriented Programming (POP) & Object Oriented
Programming (OOP)
Data abstraction :
Abstraction refers to the act of representing essential features without
including the back ground details or explanation. Classes use the concept of abstraction
and are defined as a list of attributes such as size, weight, cost and functions to operate on
these attributes. They encapsulate all essential properties of the object that are to be
created. The attributes are called as data members as they hold data and the functions
which operate on these data are called as member functions.
Class use the concept of data abstraction so they are called abstract data type (ADT)
Polymorphism: Polymorphism comes from the Greek words “poly” and “morphism”.
“poly” means many and “morphism” means form i.e.. many forms. Polymorphism means
the ability to take more than one form. For example, an operation have different behavior
in different instances. The behavior depends upon the type of the data used in the
operation.
Different ways to achieving polymorphism in C++ program:
1) Function overloading 2)
Operator overloading #include<iostream>
usin
g
nam
espa
ce
std;
int
main
()
{int a=4; a=a<<2;
cout<<”a=
”<<a<<en
dl; return
0;
}
Inheritance: Inheritance is the process by which one object can acquire the properties of
another.
Inheritance is the most promising concept of OOP, which helps realize the goal of
constructing software from reusable parts, rather than hand coding every system from
scratch. Inheritance not only supports reuse across systems, but also directly facilitates
extensibility within a system. Inheritance coupled with polymorphism and dynamic binding
minimizes the amount of existing code to be modified while enhancing a system.
When the class child, inherits the class parent, the class child is referred to as
derived class (sub class) and the class parent as a base class (super class). In this case, the
class child has two parts: a derived part and an incremental part. The derived part is
inherited from the class parent. The incremental part is the new code written specifically
for the class child.
Dynamic binding:
Binding refers to linking of procedure call to the code to be executed in response to
the call. Dynamic binding(or late binding) means the code associated with a given
procedure call in not known until the time of call at run time.
Message passing:
An object oriented program consists of set of object that communicate with each other.
Objects communicates with each other by sending and receiving information .
A message for an object is a request for execution of a procedure and
there fore invoke the function that is called for an object and generates result
APPLICATION OF OOP:
The most popular application of oops up to now, has been in the area of user interface
design such as windows.
There are hundreds of windowing systems developed using oop techniques.
Real business systems are often much more complex and contain many more objects
with complicated attributes and methods.
Oop is useful in this type of applications because it can simplify a complex problem.
The promising areas for application of oop includes.
1. Real – Time systems.
2. Simulation and modeling
3. Object oriented databases.
4. Hypertext,hypermedia and expertext.
5. Al and expert systems.
6. Neural networks and parallel programming.
7. Dicision support and office automation systems.
8. CIM / CAM / CAD system
The statement cin>>n; is an input statement and causes the program to wait for the user to
type in a number. The number keyed is placed on the variable “n”. The identifier cin is a
predefined object in C++ that corresponds to the standard input stream. The operator >> is
known as extraction operator. It extracts the value from the keyboard and assigns it to the
value variable on its right.
Keyboard
e.g.
int i; //this declaration is done outside and before main()
5. SUB PROGRAM OR FUNCTION SECTION : This has all the sub programs or the
functions which our program needs.
void display()
{
cout<<”C++ is better that C”;
}
SIMPLE „C++‟ PROGRAM:
#include<iostream> using
namespace std; void
display()
{
cout<<”C++ is better that C”;
}
int main()
{
display()
}
namespace:
namespace is used to define a scope that could hold
global identifiers. ex:-namespace scope for c++ standard
library.
A classes ,functions and templates are declared within the
namespace named std using namespace std;-->directive can be
used.
namespace namespace_name
{
//declarations of variables.functions,classes etc...
}
ex:
#include
<iostrea
m> using
namespa
ce std;
namespa
ce
sample
{`
int m;
void display(int n)
{
cout<<"in namespace N="<<n<<endl;
}
}
using
namespace
sample; int
main()
{
i
n
t
a
=
5
;
m
=
1
0
0
;
display(200);
cout<<"M in sample name
space:"<<sample::m; return 0;}
#include<iostream>
This directive causes the preprocessor to add content of iostream file
to the program. some old versions of C++ used iostream.h .if complier
does not support ANSI (american nation standard institute) C++ then
use header file iostream.h
ABSTRACTION
#include <iostream>
private:
// private variables
int a, b, c;
public:
a = x;
b = y;
c = a + b;
};
int main()
Summation s;
s.sum(5, 4);
return 0;
Output:
Example of Encapsulation:
#include <iostream>
class EncapsulationExample {
private:
int a;
public:
void set(int x)
a = x;
int get()
{
return a;
};
// main function
int main()
EncapsulationExample e1;
e1.set(10);
cout<<e1.get();
return 0;
Output:
or example, we can create a Circle class that inherits from Shape and implements
the area and perimeter functions:
#include <iostream>
using namespace std;
class Shape
{
public:
virtual double area() = 0;
virtual double perimeter() = 0;
};
double area()
{
return 3.142 * radius * radius;
}
double perimeter()
{
return 2 * 3.142 * radius;
}
};
int main()
{
double a,p;
Circle circle(5);
a = circle.area();
p = circle.perimeter();
cout<<"Area of the circle = "<<a<<endl;
cout<<"Perimeter of the circle = "<<p<<endl;
return 0;
}
Inheritance in C++
The capability of a class to derive properties and characteristics from another class is
called Inheritance. Inheritance is one of the most important feature of Object Oriented
Programming.
Sub Class: The class that inherits properties from another class is called Sub class or
Derived Class.
Super Class:The class whose properties are inherited by sub class is called Base Class or
Super class.
Note: A derived class doesn’t inherit access to private data members. However, it does
inherit a full parent object, which contains any private members which that class declares.
// C++ program to demonstrate implementation
// of Inheritance
#include <bits/stdc++.h>
using namespace std;
//Base class
class Parent
{
public:
int id_p;
};
//main function
int main()
{
Child obj1;
return 0;
}
Output:
Child id is 7
Parent id is 91
In the above program the ‘Child’ class is publicly inherited from the ‘Parent’ class so the
public data members of the class ‘Parent’ will also be inherited by the class ‘Child’.
Modes of Inheritance
1. Public mode: If we derive a sub class from a public base class. Then the public
member of the base class will become public in the derived class and protected members of
the base class will become protected in derived class.
2. Protected mode: If we derive a sub class from a Protected base class. Then both
public member and protected members of the base class will become protected in derived
class.
3. Private mode: If we derive a sub class from a Private base class. Then both public
member and protected members of the base class will become Private in derived class.
Note : The private members in the base class cannot be directly accessed in the derived
class, while protected members can be directly accessed. For example, Classes B, C and D
all contain the variables x, y and z in below example. It is just question of access.
class C : protected A
{
// x is protected
// y is protected
// z is not accessible from C
};
1. Single Inheritance: In single inheritance, a class is allowed to inherit from only one
class. i.e. one sub class is inherited by one base class only.
Syntax:
class subclass_name : access_mode base_class
{
//body of subclass
};
// C++ program to explain
// Single inheritance
#include <iostream>
using namespace
std;
// base class
class Vehicle {
public:
Vehicle()
{
cout << "This is a Vehicle" << endl;
}
};
};
// main function
int main()
{
// creating object of sub class will
// invoke the constructor of base classes
Car obj;
return 0;
}
Output:
This is a vehicle
Here, the number of base classes will be separated by a comma (‘, ‘) and access mode for
every base class must be specified.
};
// main function
int main()
{
// creating object of sub class will
// invoke the constructor of base classes
Car obj;
return 0;
}
Output:
This is a Vehicle
This is a 4 wheeler Vehicle
// base class
class Vehicle
{
public:
Vehicle()
{
cout << "This is a Vehicle" << endl;
}
};
class fourWheeler: public Vehicle
{ public:
fourWheeler()
{
cout<<"Objects with 4 wheels are vehicles"<<endl;
}
};
// sub class derived from two base classes
class Car: public fourWheeler{
public:
car()
{
cout<<"Car has 4 Wheels"<<endl;
}
};
// main function
int main()
{
//creating object of sub class will
//invoke the constructor of base classes
Car obj;
return 0;
}
output:
This is a Vehicle
Objects with 4 wheels are vehicles Car
has 4 Wheels
4. Hierarchical Inheritance: In this type of inheritance, more than one sub class is
inherited from a single base class. i.e. more than one derived class is created from a single
base class.
// base class
class Vehicle
{
public:
Vehicle()
{
cout << "This is a Vehicle" << endl;
}
};
};
};
// main function
int main()
{
// creating object of sub class will
// invoke the constructor of base class
Car obj1;
Bus obj2;
return 0;
}
Output:
This is a Vehicle
This is a Vehicle
5. Hybrid (Virtual) Inheritance: Hybrid Inheritance is implemented by combining
more than one type of inheritance. For example: Combining Hierarchical inheritance and
Multiple Inheritance.
Below image shows the combination of hierarchical and multiple inheritance:
#include <iostream>
using namespace std;
// base class
class Vehicle
{
public:
Vehicle()
{
cout << "This is a Vehicle" << endl;
}
};
//base class
class Fare
{
public:
Fare()
{
cout<<"Fare of Vehicle\n";
}
};
};
};
// main function
int main()
{
// creating object of sub class will
// invoke the constructor of base class
Bus obj2;
return 0;
}
Output:
This is a Vehicle
Fare of Vehicle
A special case of hybrid inheritance : Multipath inheritance:
A derived class with two base classes and these two base classes have one common base
class is called multipath inheritance. An ambiguity can arrise in this type of inheritance.
Consider the following program:
// C++ program demonstrating ambiguity in Multipath Inheritance
#include<iostream.h>
#include<conio.h>
class ClassA
{
public:
int a;
};
void main()
{
ClassD obj;
obj.b = 20;
obj.c = 30;
obj.d = 40;
}
Output:
A from ClassB : 10 A
from ClassC : 100 B :
20
C : 30
D : 40
In the above example, both ClassB & ClassC inherit ClassA, they both have single copy of
ClassA. However ClassD inherit both ClassB & ClassC, therefore ClassD have two copies
of ClassA, one from ClassB and another from ClassC.
If we need to access the data member a of ClassA through the object of ClassD, we must
specify the path from which a will be accessed, whether it is from ClassB or ClassC, bco’z
compiler can’t differentiate between two copies of ClassA in ClassD.
class ClassA
{
public:
int a;
};
void main()
{
ClassD obj;
obj.b = 20;
obj.c = 30;
obj.d = 40;
}
Output:
A : 100
B : 20
C : 30
D : 40
According to the above example, ClassD has only one copy of ClassA, therefore, statement
4 will overwrite the value of a, given at statement 3.
As we can see from the figure that data members/function of class A are inherited twice to
class D. One through class B and second through class C. When any data / function member
of class A is accessed by an object of class D, ambiguity arises as to which data/function
member would be called? One inherited through B or the other inherited through C. This
confuses compiler and it displays error.
Example: To show the need of Virtual Base Class in C++
#include <iostream>
using namespace std;
class A {
public:
void show()
{
cout << "Hello form A \n";
}
};
class B : public A {
};
class C : public A {
};
int main()
{
D object;
object.show();
}
Compile Errors:
prog.cpp: In function 'int main()':
prog.cpp:29:9: error: request for member 'show' is ambiguous
object.show();
^
prog.cpp:8:8: note: candidates are: void A::show()
void show()
^
prog.cpp:8:8: note: void A::show()
Syntax 2:
class C : public virtual A
{
};
Note: virtual can be written before or after the public. Now only one copy of data/function
member will be copied to class C and class B and class A becomes the virtual base class.
Virtual base classes offer a way to save space and avoid ambiguities in class hierarchies that
use multiple inheritances. When a base class is specified as a virtual base, it can act as an
indirect base more than once without duplication of its data members. A single copy of its
data members is shared by all the base classes that use virtual base.
Example 1
#include <iostream>
using namespace std;
class A {
public:
int a;
A() // constructor
{
a = 10;
}
};
int main()
{
D object; // object creation of class d
cout << "a = " << object.a << endl;
return 0;
}
Output:
a = 10
Explanation :The class A has just one data member a which is public. This class is
virtually inherited in class B and class C. Now class B and class C becomes virtual base
class and no duplication of data member a is done.
Example 2:
#include <iostream>
using namespace
std;
class A { public:
void show()
{
cout << "Hello from A \n";
}
};
int main()
{
D object; object.show();
}
Output:
Hello from A
Polymorphism word is the combination of "poly," which means many + "morphs," which means forms,
which together means many forms. Polymorphism in C++ is when the behavior of the same object or
function is different in different contexts. Let's take a real-world example of the word right can mean
different things in a different context.
I was right. In the above sentence, the word right means "correct".
Please take a right turn. The word right refers to the "right direction" in the above sentence.
The + operator in C++ is one of the best examples of polymorphism. The + operator is used to add two
integers as follows :
#include <bits/stdc++.h>
using namespace std;
int main() {
int a = 10;
int b = 32;
Output:
Ans:42
However, + is also used to concatenate two string operands. The + operator is used to concatenate two
strings as follows :
#include <bits/stdc++.h>
using namespace std;
int main() {
string a = "poly";
string b = "morphism";
Output:
Overloaded functions are called by comparing the data types and number of parameters. This type of
information is available to the compiler at the compile time. Thus, the suitable function to be called will be
chosen by the C++ compiler at compilation time.
Function Overloading
When we have two functions with the same name but different parameters, different functions are called
depending on the number and data types of parameters. This is known as function overloading
The names of the functions and return types are the same but differ in the type of arguments.
The name of the functions and return types are the same, but they differ in the number of
arguments.
Let's understand with an example :
#include <bits/stdc++.h>
using namespace std;
class Temp
{
private:
int x = 10;
double x1 = 10.1;
public:
void add(int y)
{
cout << "Value of x + y is: " << x + y << endl;
}
// Differ in the type of argument.
void add(double d)
{
cout << "Value of x1 + d is: " << x1 + d << endl;
}
// Differ in the number of arguments.
void add(int y, int z)
{
cout << "Value of x + y + z is: " << x + y + z << endl;
}
};
int main() {
Temp t1;
t1.add(10);
t1.add(11.1);
t1.add(12,13);
return 0;
}
Output :
Value of x + y is: 20
Value of x1 + d is: 21.2
Value of x + y + z is: 35
Explanation:
Operator Overloading
When an operator is updated to be used for user-defined data types (objects etc.), this is known as operator
overloading. To use operator overloading, at least one operand must be a user-defined data type.
Note:
Boolean algebra : !=, ==, > ,< ,>=, <= , && ,||
Bit manipulation : &, |, ^ ,<< ,>> and |=, &= ,>>=, <<=, ^=
Note:
New and Delete operators can be overloaded globally, or they can be overloaded for specific
classes. If these operators are overloaded using the member function for a class, they are
overloaded only for that specific class.
Syntax :
#include<iostream>
class Count {
int x;
public:
// Constructor
Count(int X = 0) {
this -> x = X;
}
// Overloading the ++ operator.
Count operator++() {
Count c;
c.x = ++x;
return c;
}
// Print value of x.
void print() {
cout << x << endl;
}
};
int main() {
Count c1(42);
Count c2 = ++c1;
cout << "After using ++ operator: ";
c2.print();
Output :
Before using ++ operator: 42
After using ++ operator: 43
Explanation:
In the above example, the ++ operator is overloaded for a user-defined data type, an object of
the Count class.
Count c1(42); creates the object of Count type, in which data member x will have a value equal
to 42.
Count c2 = ++c1; this calls the ++ operator function on t1, which makes the value of x as 43.
Runtime Polymorphism
Runtime polymorphism occurs when functions are resolved at runtime rather than compile time when a
call to an overridden method is resolved dynamically at runtime rather than compile time. It's also known
as late binding or dynamic binding.
Runtime polymorphism is achieved using a combination of function overriding and virtual functions.
The following sections will show an example of overriding with and without the virtual keyword.
Function Overriding is when more than one method of the derived class has the same name, the
same number of parameters, and the same parameter type as of base class.
Syntax :
class Polygon {
protected: int height,
width;
public: void set_values(int x, int y) {
width = x;
height = y;
}
int area() {
return 0;
}
};
int main() {
Rectangle rect;
Triangle trgl;
Polygon poly;
cout << "Area of Rectangle is: " << ppoly1 -> area() << '\n';
cout << "Area of Triangle is: " << ppoly2 -> area() << '\n';
cout << "Area of Polygon is: " << ppoly3 -> area() << '\n';
return 0;
}
Output:
Area of Rectangle is: 0
Area of Triangle is: 0
Area of Polygon is: 0
Explanation:
In this example, the width, height, and functions set values and area are shared by all three classes
(Polygon, Rectangle, and Triangle).
Three references to Polygon are declared in the main function (ppoly1, ppoly2, and ppoly3 ). These
are given the addresses rect and trgl poly, which are objects of type Rectangle, Triangle,
and Polygon, respectively. Rectangle and Triangle are Polygon-derived classes; therefore, such
assignments are permitted.
ppoly1 -> set_values (10, 20); is similar to rect.set_values (10, 20); and ppoly2 -> set_values (10,
20); is similar to trgl.set_values (10, 20);
ppoly1 -> area() and ppoly1 -> area() is called this will call area function of the base class Polygon.
This happens due to static linkage, which implies that the compiler only sets the call to the area()
once in the base class.
To overcome this problem, the concept of virtual pointers is introduced.
A virtual function in C++ is a base class member function. In a derived class, we can redefine it. The
virtual function must be declared using the keyword virtual in the base class. A class that declares or
inherits a virtual function is called a polymorphic class.
Syntax :
class Polygon {
protected: int height,
width;
public: void set_values(int x, int y) {
width = x;
height = y;
}
virtual int area() {
return 0;
}
};
}
};
int main() {
Rectangle rect;
Triangle trgl;
Polygon poly;
cout << "Area of Rectangle is: " << ppoly1 -> area() << '\n';
cout << "Area of Triangle is: " << ppoly2 -> area() << '\n';
cout << "Area of Polygon is: " << ppoly3 -> area() << '\n';
return 0;
}
Output:
Area of Rectangle is: 200
Area of Triangle is: 100
Area of Polygon is: 0
Explanation:
ppoly1 -> area() is called it will call area function of Rectangle class.
ppoly2 -> area() is called it will call area function of Triangle class.
This is because we used the virtual keyword to make the base class Polygon method area virtual in
this code. The confusion over which function to call will be resolved at runtime, resulting in the
desired outcome.
A Pure Virtual Function is a virtual function declared in the base class without definition. In simple words,
it does nothing in the base class. But the derived class must provide an implementation for this function.
Otherwise, we'll get a compilation error.
Syntax :
#include <bits/stdc++.h>
return 0;
}
Output:
Inside derived class
Explanation:
To check what error we get if we don't provide the definition of func() in Derived, comment out the
definition and re-compile the above code. We get the following error:
g++ /tmp/main.cpp
/tmp/main.cpp: In function 'int main()':
/tmp/main.cpp:19:22: error: invalid new-expression of abstract class type 'Derived'
19 | b1 = new Derived();
| ^
/tmp/main.cpp:9:7: note: because the following virtual functions are pure within 'Derived':
9 | class Derived : public Base
| ^~~~~~~
/tmp/main.cpp:6:17: note: 'virtual void Base::func()'
6 | virtual void func() = 0; // Pure Virtual Function
| ^~~~
Conclusion
Polymorphism in C++ is when the behavior of the same object or function is different in different
contexts.
It is of two types: Compile-time Polymorphism and Runtime Polymorphism.
In Compile Time Polymorphism, the function to be invoked is decided at the compile time only. It
is achieved using a function or operator overloading.
In Runtime Polymorphism, the function invoked is decided at the Run-time. It is achieved using
function overriding and virtual functions.
The virtual function must be declared using the keyword "virtual" in the base class.
A Pure Virtual Function is a virtual function declared in the base class without definition.