Unit 4
Unit 4
Unit 4
What is C++ ?
• C++ is a general purpose, case-sensitive, free-form
programming language that supports object-oriented,
procedural and generic programming.
• C++ is a middle-level language, as it encapsulates both high
and low level language features.
C++ history
• C++ programming language was developed in 1980 by Bjarne
Stroustrup at bell laboratories of AT&T (American Telephone &
Telegraph), located in U.S.A.
• Bjarne Stroustrup is known as the founder of C++ language.
• It was develop for adding a feature of OOP (Object Oriented
Programming) in C without significantly changing the C
component.
• C++ programming is "relative" (called a superset) of C, it means
any valid C program is also a valid C++ program.
Object-Oriented Programming (OOPs)
C++ supports the object-oriented programming, the four
major pillar of object-oriented programming (OOPs) used in
C++ are:
• Inheritance
• Polymorphism
• Encapsulation
• Abstraction
C++ Standard Libraries
• Standard C++ programming is divided into three important parts:
• The core library includes the data types, variables and literals, etc.
• The standard library includes the set of functions manipulating
strings, files, etc.
• The Standard Template Library (STL) includes the set of methods
manipulating a data structure.
Usage of C++
By the help of C++ programming language, we can develop different
types of secured and robust applications:
• Window application
• Client-Server application
• Device drivers
• Embedded firmware etc
Applications of C++ Programming
• Application Software Development - C++ programming has been
used in developing almost all the major Operating Systems like
Windows, Mac OSX and Linux. Apart from the operating systems, the
core part of many browsers like Mozilla Firefox and Chrome have
been written using C++. C++ also has been used in developing the
most popular database system called MySQL.
• Programming Languages Development - C++ has been used
extensively in developing new programming languages like C#, Java,
JavaScript, Perl, UNIX’s C Shell, PHP and Python, and Verilog etc.
• Computation Programming - C++ is the best friends of
scientists because of fast speed and computational
efficiencies.
• Games Development - C++ is extremely fast which allows
programmers to do procedural programming for CPU
intensive functions and provides greater control over
hardware, because of which it has been widely used in
development of gaming engines.
• Embedded System - C++ is being heavily used in developing
Medical and Engineering Applications like softwares for MRI
machines, high-end CAD/CAM systems etc.
Difference between C and C++
C++ Features
C++ Basic Syntax
• When we consider a C++ program, it can be defined as a
collection of objects that communicate via invoking each
other's methods. Let us now briefly look into what a class,
object, methods, and instant variables mean.
• Object − Objects have states and behaviors. Example: A dog
has states - color, name, breed as well as behaviors -
wagging, barking, eating. An object is an instance of a class.
• Class − A class can be defined as a template/blueprint that
describes the behaviors/states that object of its type
support.
• Methods − A method is basically a behavior. A class can
contain many methods. It is in methods where the logics are
written, data is manipulated and all the actions are executed.
• Instance Variables − Each object has its unique set of
instance variables. An object's state is created by the values
assigned to these instance variables.
C++ First Program
#include <iostream>
using namespace std;
int main() {
cout << "Hello World";
return 0;
}
Explanation of the Code
• The C++ language defines several headers, which contain
information that is either necessary or useful to your
program. For this program, the header <iostream> is
needed.
• The line using namespace std; tells the compiler to use the
std namespace. Namespaces are a relatively recent addition
to C++.
• The next line '// main() is where program execution begins.'
is a single-line comment available in C++. Single-line
comments begin with // and stop at the end of the line.
• The line int main() is the main function where program
execution begins.
• The next line cout << "Hello World"; causes the message
"Hello World" to be displayed on the screen.
• The next line return 0; terminates main( )function and
causes it to return the value 0 to the calling process.
C++ Identifiers
• A C++ identifier is a name used to identify a variable,
function, class, module, or any other user-defined item.
• An identifier starts with a letter A to Z or a to z or an
underscore (_) followed by zero or more letters, underscores,
and digits (0 to 9).
• C++ does not allow punctuation characters such as @, $, and
% within identifiers.
• C++ is a case-sensitive programming language.
• Thus, Manpower and manpower are two different
identifiers in C++.
Here are some examples of acceptable identifiers
abc
move_name
a_123
myname50
_temp
J
a23b9
retVal
C++ Keywords
Comments in C++
• Program comments are explanatory statements that you can
include in the C++ code.
• These comments help anyone reading the source code.
• All programming languages allow for some form of
comments.
• C++ supports single-line and multi-line comments.
• All characters available inside any comment are ignored by
C++ compiler.
Example
C++ comments start with /* and end with */. For example −
/* This is a comment */
multiply()
{
;
}
Parts of a function
main function
{
function prototype declaration
function call
-------;
}
function declaratory/definition
{
------;
return statement
}
Function
A function prototype is aprototype
declaration of a function that tells the program about
the type of value returned by the function, name of function, number and type
of arguments.
Syntax: Return_type function_name (parameter list/argument);
int add(int,int);
void add(void);
int add(float,int);
4 parts
Variable declaration
i. Return type Data_type variable_name ;
ii. Function name int x=5;
float marks;
iii. Argument list int price;
iv. Terminating semicolon
Function call
A function must be called by its name followed by argument list enclosed
in semicolon.
Syntax: function_name (parameter list/argument);
add(x,y);
add(40,60);
add(void); or add();
Note: data type not to be mentioned.
int float
Now suppose the function return some integer value, you can use a
variable to store that value.
i.e z=add(x,y);
Parts of a function
main function
{
function prototype declaration
function call
}
function declaratory/definition
{
return statement
}
Function definition 2 parts
Syntax: function_type function_name(parameter list) Function
{ header
Note: no semicolon in header
Local variable declaration;
Function
Function body statement;
body
Return statement;
}
Example: int add(int,int); //prototype
Z=add(x,y); //function call
int main()
{
print(); function_name(parameter list/argument);
return 0;
}
void print() function_type function_name(parameter list)
{
cout<<“2 is even no.”<<endl;
}
Parts of a function
main function
{
function prototype declaration Return_type function_name(arguments); eg: int add(int);
function call
function_name(actual arguments); eg: add(a);
-------;
}
void sqr()
{
int no;
cout<<“enter a no.”;
cin>>no;
cout<<“square of”<<no<<“is”<<no*no;
}
ii. Function will not return any value but passes argument
#include<iostream.h>
#include<conio.h>
void add(int,int);
int main()
{
int a,b;
add(a,b);
cout<<“enter values of a and b”<<endl;
cin>>a>>b;
add(a,b);
a b
getch();
return 0;
void add(int x,int y);
}
void add(int x,int y)
{
int c;
c=x+y;
cout<<“addition is”<<c;
}
iii) Function with arguments and return value
main function
{
int sqr(int); //function prototype
int a,ans;
cout<<“enter a number”;
cin>>a;
ans=sqr(a); //function call
cout<<“square of number is”<<ans;
getch();
return 0;
}
int add(void);
{
int a,b;
cout<<“enter 2 nos”;
cin>>a>>b;
return(a+b);
}
Pointers
• Special type of variables which hold the address of another variable
i.e no values or datas are stored but it points to another variable
where data is stored.
int a=100;
Pointer stores
1)a→ name this memory
location, no
direct value is
100 → 2)value stored.
3)address
a
Declaration: Data_type *variable_name;
100
int a=100; address 1
int *ptr;
Intialisation: ptr=&a; //referencing
“Address of” operator
ptr
or address 1
int a=100;
Pointer initialisation int *ptr=&a; address 2
and declaration
Note: a pointer can be used to point to another pointer also i.e it can
store the address of another pointer.
a
100
int a=100; address 1 cout<<a; //100
int *ptr=&a; cout<<*ptr;//100
ptr cout<< **ptr1; //100
int **ptr1=&ptr;
address 1
address 2
Note: pointer 1 points to address of ptr.
ptr1
address 2
address 3
#include<iosream.h> Chain of pointers
#include<conio.h> p1 p2
a
int main()
100 address 1 address 2
{
int a=100; address 1 address 2 address 3
int *p1;
int * *p2;
p1=&a; //p1 points to address of a
p2=&p1; // p2 points to address of p1
cout<<“address of a”<<&a;
cout<<“address of a”<<p1;
cout<<“value of a”<< *p1;
cout<<“value of a”<< * *p2;
cout<<p2;
cout<< *p2;
getch();
}
Reference variable in C++
When a variable is declared as reference, it becomes an alternative
name for an existing variable. A variable can be declared as reference by
putting ‘&’ in the declaration.
int a=100;
Now we will use a reference variable i.e two names
for same memory location.
a
int a=100;
100 int &ref=a; //initialization and declaration
getch();
}
Call by value
A function can be invoked in two manners
(i)call by value
(ii)call by reference
The call by value method copies the value of actual parameters into formal
parameters i.e the function creates its own copy of arguments and uses
them.
Values of variables a
add(a,b); and b are passed to
Call by value
} X,Y
where the values of void add(int x,int y); Now if you change
variable are passed
to functions { the value of X and Y,
those changes are
--------; not seen in a and b
}
#include<iostream.h>
/* program to illustrate the concept of call by
#include<conio.h>
value */
void add(int,int);
int main()
{
int a,b;
cout<<“enter values of a and b”<<endl;
cin>>a>>b;
add(a,b);
getch();
return 0;
}
void add(int x,int y)
{
int c;
c=x+y;
cout<<“addition is”<<c;
Call by reference
In call by reference method in place of calling a value to the function being
called , a reference to the original variable is passed .i.e the same variable value
can be accessed by any of the two names.
In function call
add(a,b); We write reference
variable for formal
} arguments
• Normal function
• Inside the main() method, when the function funx() is called, the control is transferred to the
definition of the called function.
• The addresses from where the function is called and the definition of the function are different.
• This control transfer takes a lot of time and increases the overhead.
• Inline Function
• When the inline function is encountered, then the definition of the function is copied to it.
• In this case, there is no control transfer which saves a lot of time and also decreases the
overhead.
Let's understand through an example
#include <iostream>
using namespace std;
inline int add(int a, int b)
{
return(a+b);
}
int main()
{
cout<<"Addition of 'a' and 'b' is:"<<add(2,3);
return 0;
}
Once the compilation is done, the code would
be like as shown as below:
#include<iostream>
using namespace std;
inline int add(int a, int b)
{
return(a+b);
}
int main()
{
cout<<"Addition of 'a' and 'b' is:"<<return(2+3);
return 0;
}
Why do we need an inline function in C++?
• The main use of the inline function in C++ is to save memory space.
• Whenever the function is called, then it takes a lot of time to execute
the tasks, such as moving to the calling function.
• If the length of the function is small, then the substantial amount of
execution time is spent in such overheads, and sometimes time taken
required for moving to the calling function will be greater than the
time taken required to execute that function.
Macro vs. Inline functions
• The solution to this problem is to use macro definitions known as
macros. The preprocessor macros are widely used in C, but the major
drawback with the macros is that these are not normal functions which
means the error checking process will not be done during the
compilation.
• C++ has provided one solution to this problem. In the case of function
calling, the time for calling such small functions is huge, so to
overcome such a problem, a new concept was introduced known as an
inline function. When the function is encountered inside the main()
method, it is expanded with its definition thus saving time.
If we create two or more members having the same
name but different in number or type of parameter, it is
known as C++ overloading.
In C++, we can overload:
• methods,
• constructors, and
• indexed properties
Types of overloading in C++ are:
C++ Function Overloading
• Function Overloading is defined as the process of
having two or more function with the same name, but
different in parameters is known as function
overloading in C++.
• In function overloading, the function is redefined by
using either different types of arguments or a
different number of arguments.
• It is only through these differences compiler can
differentiate between the functions.
• The advantage of Function overloading is that it
increases the readability of the program because you
don't need to use different names for the same action
Function Overloading and Ambiguity
When the compiler is unable to decide which function is to be invoked
among the overloaded function, this situation is known as function
overloading.
When the compiler shows the ambiguity error, the compiler does not
run the program.
Causes of Function Overloading:
• Type Conversion.
• Function with default arguments.
• Function with pass by reference.
#include<iostream>
using namespace std;
void fun(int);
void fun(float);
void fun(int i)
{
std::cout << "Value of i is : " <<i<< std::endl;
}
void fun(float j)
{
std::cout << "Value of j is : " <<j<< std::endl;
}
int main()
{
fun(12);
fun(1.2);
return 0;
}
Explanation
• example shows an error "call of overloaded 'fun(double)' is
ambiguous".
• The fun(10) will call the first function.
• The fun(1.2) calls the second function according to our
prediction. But, this does not refer to any function as in C++,
all the floating point constants are treated as double not as a
float.
• If we replace float to double, the program works.
• Therefore, this is a type conversion from float to double.
Default Parameter
• In C++ programming, we can provide default values
for function parameters.
• If a function with default arguments is called without passing
arguments, then the default parameters are used.
• However, if arguments are passed while calling the function, the
default arguments are ignored.
Rules of default arguments
• If you assign default value to an argument, the subsequent arguments must have default values
assigned to them, else you will get compilation error.
• Lets see some valid and invalid cases.
• Valid: Following function declarations are valid –
• int sum(int a=10, int b=20, int c=30);
• int sum(int a, int b=20, int c=30);
• int sum(int a, int b, int c=30);
• Invalid: Following function declarations are invalid –
• int sum(int a=10, int b, int c=30);
• int sum(int a, int b=20, int c);
• int sum(int a=10, int b=20, int c);
Friend Functions in C++
• Friend functions of the class are granted permission to access private and
protected members of the class in C++. They are defined globally outside the
class’ scope. Friend functions are not member functions of the class. So, what
exactly is the friend function?
.
Objects and Classes
int main() {
MyClass myObj; // Create an object of MyClass
int main() {
MyClass myObj; // Create an object of MyClass
myObj.myMethod(); // Call the method
return 0;
}
Outside Example
class MyClass { // The class
public: // Access specifier
void myMethod(); // Method/function declaration
};
// Method/function definition outside the class
void MyClass::myMethod() {
cout << "Hello World!";
}
int main() {
MyClass myObj; // Create an object of MyClass
myObj.myMethod(); // Call the method
return 0;
}
#include <iostream>
using namespace std;
class Car {
public:
int speed(int maxSpeed);
};
int Car::speed(int maxSpeed) {
return maxSpeed;
}
int main() {
Car myObj; // Create an object of Car
cout << myObj.speed(200); // Call the method with
an argument
return 0;
}
this Pointer
In C++ programming, this is a keyword that refers to
the current instance of the class.
• It can be used to pass current object as a
parameter to another method.
• It can be used to refer current class instance
variable.
#include <iostream>
using namespace std;
class Employee {
public:
int id; //data member (also instance variable)
string name; //data member(also instance variable)
float salary;
Employee(int id, string name, float salary)
{
this->id = id;
this->name = name;
this->salary = salary;
}
void display()
{
cout<<id<<" "<<name<<" "<<salary<<endl;
}
};
int main(void) {
Employee e1 =Employee(101, "Sonoo", 890000); //creating an object of Employee
Employee e2=Employee(102, "Nakul", 59000); //creating an object of Employee
e1.display();
e2.display();
return 0;
}
C++ Access Specifiers
In C++, there are three access specifiers:
public - members are accessible from outside the class
private - members cannot be accessed (or viewed) from
outside the class
protected - members cannot be accessed from outside
the class, however, they can be accessed in inherited
classes.
Example
class MyClass {
public: // Public access specifier
int x; // Public attribute
private: // Private access specifier
int y; // Private attribute
};
int main() {
MyClass myObj;
myObj.x = 25; // Allowed (public)
myObj.y = 50; // Not allowed (private)
return 0;
}
Note: By default, all members of a class are private if you don't
specify an access specifier:
class MyClass {
int x; // Private attribute
int y; // Private attribute
};
Constructors
• A constructor in C++ is a special method that is
automatically called when an object of a class is
created.
• To create a constructor, use the same name as the
class, followed by parentheses ():
Note: The constructor has the same name as the class,
it is always public, and it does not have any return
value.
Constructor in C++
• A Constructor is a member function of a class.
• It is mainly used to initialize the objects of the class.
• It has the same name as the class.
• When an object is created, the constructor is automatically
called.
• It is a special kind of member function of a class.
Example
int main() {
MyClass myObj; // Create an object of MyClass
(this will call the constructor)
return 0;
}
Constructor Parameters