0% found this document useful (0 votes)
7 views

C++ Programming

Introduction and ppt on c++ programming language for beginners

Uploaded by

Time pass
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

C++ Programming

Introduction and ppt on c++ programming language for beginners

Uploaded by

Time pass
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 144

Programming

Introduction to C++

Presented By:
Ms. Nidhi Agrawal
Assistant Professor, SOC IPS Academy
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 2

Introduction to C++
 C++ is a statically typed, compiled, general-purpose,
case-sensitive, free-form programming language that
supports procedural, object-oriented, and generic
programming.

 C++ was developed by Bjarne Stroustrup starting in


1979 at Bell Labs in Murray Hill, New Jersey, as an
enhancement to the C language and originally named
C with Classes but later it was renamed C++ in 1983.
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 3

C++ History
 C developed by Dennis Ritchie at AT&T
Bell Labs in the 1970s.
 Used to maintain UNIX systems
 Many commercial applications written in c

 C++ developed by Bjarne Stroustrup at AT&T


Bell Labs in the 1980s.
 Overcame several shortcomings of C
 Incorporated object oriented programming
 C remains a subset of C++
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 4

Why use C++


1. C++ In Database
2. C++ In Operating Systems
3. C++ In Web Browsers
4. C++ In Graphics
5. C++ is Portable
6. C++ has a Large Community
7. C++ has Abundant Library Support
8. C++ In Compilers
Difference between procedural
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 5

programming and oops


 In procedural programming, program is
divided into small parts called functions.
In object oriented programming, program is
divided into small parts called
objects. Procedural programming follows
top down approach. Procedural
programming does not have any proper way
for hiding data so it is less secure.
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 6

OOP Characteristics
 Encapsulation
 Information hiding
 Objects contain their own data and algorithms

 Inheritance
 Writing reusable code
 Objects can inherit characteristics from other objects

 Polymorphism
 A single name can have multiple meanings depending
on its context
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 7

C++ keywords
 Keywords appear in blue in Visual C++.
 Each keyword has a predefined purpose in the language.
 Do not use keywords as variable and constant names!!
 The complete list of keywords is on page 673 of the
textbook.
 We shall cover the following keywords in this class:
bool, break, case, char, const, continue,
do, default, double, else, extern, false,
float, for, if, int, long, namespace,
return, short, static, struct, switch,
typedef, true, unsigned, void, while
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 8

A Sample C++ Program

 A simple C++ program begins this way


#include <iostream.h >
using namespace std;
int main()
{
 And ends this way
return 0;
}
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 9

Explanation of code
 <iostream>
It is used to define the cout, cin and cerr objects, which correspond to
standard output stream, standard input stream and standard error stream,
respectively.
 Standard output stream (cout)

The cout is a predefined object of ostream class. It is connected with the


standard output device, which is usually a display screen. The cout is used
in conjunction with stream insertion operator (<<) to display the output on a
console
 Standard input stream (cin)

The cin is a predefined object of istream class. It is connected with the


standard input device, which is usually a keyboard. The cin is used in
conjunction with stream extraction operator (>>) to read the input from a
console.
C++ DATA TYPES

Primary data type Int, Float, Char, Void

User defined data type Structure, Union, Class, Enumeration

Derived data type Array, Function, Pointer, Reference


COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 11

C++ Enumeration
Enumerated type (enumeration) is a user-defined data type which
can be assigned some limited values. These values are defined
by the programmer at the time of declaring the enumerated type.

It is used to assign names to the integral constants which makes a


program easy to read and maintain. The keyword “enum” is
used to declare an enumeration. The following is the syntax
of enums.

Enumerator types of values are also known as enumerators. It is


also assigned by zero the same as the array. It can also be used
with switch statements.
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 12

Program
#include <iostream>
enum colors{red=5, black};
enum suit{heart, diamond=8, spade=3, club};
int main()
{
cout <<"The value of enum color : "<<red<<","<<black;
cout <<"\nThe default value of enum suit :
"<<heart<<","<<diamond<<","<<spade<<","<<club;
return 0;
}
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 13

Sample Program
#include <iostream.h>
int main()
{
cout << "Size of char : " << sizeof(char) << endl;
cout << "Size of int : " << sizeof(int) << endl;
cout << "Size of short int : " << sizeof(short int) << endl;
cout << "Size of long int : " << sizeof(long int) << endl;
cout << "Size of float : " << sizeof(float) << endl;
cout << "Size of double : " << sizeof(double) << endl;
cout << "Size of wchar_t : " << sizeof(wchar_t) << endl;
return 0;
}
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 14

C++ VARIABLES

 A variable is a name of memory location. It is used to store data.


Its value can be changed and it can be reused many times.

 It is a way to represent memory location through symbol so that


it can be easily identified.
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 15

C++ VARIABLES SCOPE


 A scope is a region of the program and broadly speaking there
are three places, where variables can be declared −

 Inside a function or a block which is called local variables.

 In the definition of function parameters which is called formal


parameters.

 Outside of all functions which is called global variables.


COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 16

Example
#include <iostream.h>
// Global variable declaration:
Int g;
int main ()
{
// Local variable declaration:
int a, b;
// actual initialization OUTPUT=???
a = 10;
b = 20;
g = a + b;
cout << g;
return 0;
}
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 17

OPERATORS
 Arithmetic operators

 Relational operators

 Logical operators

 Bitwise operators

 Assignment operators
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 18

ARITHMETIC OPERATORS

#include<iostream.h> c=a*b;
#include<conio.h> cout<<c;
void main() c=a/b;
{ cout<<c; c=a+
Int a, b,c;cout<<“enter +;
the value for a and b”;
cout<<“incrementation of a by
cin>>a>>b; one”<<c;
c=a+b; c=a--;
cout<<c; cout<<”decrementation of a by
c=a-b; one”<<c); }
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 19

RELATIONAL OPERATORS

#include<iostream.h> if(a<=b)
#include<conio.h> cout<<”a is less than or equal to b”;
void main() if(a>=b)
{ cout<<“a is greater than or equal to b”;
int a , b; if(a==b)
a=10; b=13; cout<<”a is equal to b”;
if(a<b) if(a!=b)
cout<<“a is less than b”; cout<<”a is not equal to b”;
}
if(a>b)
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 20

LOGICAL OPERATORS
#include<iostream.h> a=0; b=10;
#include<conio.h>
if(a&&b)
void main()
cout<<“condition is true”;
{
else
int a, b; a=12;
cout<<“condition is not true”;
b=10;
if(a&&b) if(!(a&&b))
cout<<“condition is true”;
cout<<”conditio }
n is true”;
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 21

BITWISE OPERATOR
Bitwise operator works on bits and perform bit-by-bit operation.

P Q P&Q P|Q P^Q

0 0 0 0 0

0 1 0 1 1

1 0 0 1 1

1 1 1 1 0
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 22

Assume if A = 60; and B = 13; now in binary format they will be as follows:
A = 0011 1100 ----> Binary Number for 60
B = 0000 1101 ----> Binary Number for 13

A&B = 0000 1100


A|B = 0011 1101
A^B = 0011 0001
~A =
1100 0011
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 23

Program
#include <iostream.h>
int main() {
int a = 7; // a = 111
int b = 5; // b = 101
cout << "Bitwise Operators\n";
cout << "a & b = " << (a&b) << "\n";
cout << "a | b = " << (a|b) << "\n";
cout << "a ^ b = " << (a^b) << "\n";
cout << "~a = " << (~a) << "\n";
cout << "~b = " << (~b) << "\n";
cout << "a >> b = " << (a>>b) << "\n";
cout << "a << b = " << (a<<b) << "\n";
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 24

OUTPUT

Bitwise Operators a & b = 5


a|b=7 a^b=2
~a = -8
~b = -6
a >> b = 0
a << b = 224
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 25

ASSIGNMENT OPERATOR
An assignment operator, in the context of the C programming language, is a
basic component denoted as "=".
Int x = 25;
x = 50;
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 26

New operators introduced

In c++ are
 Scope resolution operator ::
 new Memory allocating operator
 delete Memory release operator
 endl Line feed operator
 setw Field width operator
 insertion <<
 Extraction >>
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 27

Scope Resolution Operator In C++


 In C++ language the scope resolution operator is written "::".

 C++ supports to the global variable from a function, Local


variable is to define the same function name.

 Identify variables with use of scope resolution operator when we


use the same name for local variable and global variable ( or in
class or namespace )

 Resolution operator is placed between the front of the variable


name then the global variable is affected.If no resolution
operator is placed between the local variable is affected.
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 28

PROGRAM

#include<iostream.h>
int n = 12; //global variable
int main()
{
int n = 13; //local variable
cout << ::n << endl;
cout << n << endl;
}
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 29

OUTPUT

n=12

n=13
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 30

Manipulators:

Manipulators are the operators used to format


the data that is to be displayed on screen.The
most commonly used manipulators are endl
and setw.
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 31

ENDL
it is used in output statement and inserts a line feed. It is
similar to new line character (“\n”)
#include <iostream.h>
int main( ) {
cout << "C++ ";
cout << " Java"<<endl;
cout << “C"<<endl;
Return 0;
}
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 32

setw
this manipulator allows a specified width for a field that is to be printed on
screen and by default the value printed is right justified.This function is
available in header file iomanip.h.

#include<iostream.h>
#include<iomanip.h>

int main()
{
int s=123;
cout<<"s="<<setw(10)<<s ;
}
output
s= 123
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 33

Insertion (<<) and Extraction (>>)


operators:
the operators are use with output and input objects
ex:
cout<<”Enter n”;
cin>>n
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 34

Control statements
The flow of execution of statements in a program is called as control. Control
statement is a statement which controls flow of execution of the program.
Control statements are classified into following categories.

1.Sequential control statements

2.Conditional control statements

3.Unconditional control statements


COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 35

Sequential control statements


Sequential control statements ensures that the
instructions(or statements) are executed in the same
order in which they appear in the program. i.e. By
default system executes the statements in the
program in sequential order.
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 36

Conditional control statements

Statements that are executed when a condition is true. These statements are
divided into three categories. they are

1.Decision making statements


2.Switch case control statement or
3.Loop control statements or repetations
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 37

Decision making statements


These statements are used to control the flow of execution of a program
by making a decision depending on a condition, hence they are named as
decision making statements.

Decision making statements are of four types

1.Simple if
2.if else
3.nested if else
4.If else ladder
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 38

if statement
#include<iostream.h>
int main()
{
int a,b;
cout<<“Enter any two integers:”;
cin>>a>>b;
if(a>b)
cout<<“A is larger than B\n A=”<<a;
if(b>a)
cout<<“B is larger than A\n A=”<<b;
return 0;
}
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 39

if –else statement
#include<iostream.h>
int main()
{
int a,b;
cout<<”Enter any two integers:”;
cin>>a>>b;
if(a>b)
cout<<“A is larger than B\n A=”<<a;
else
cout<<“B is larger than A\n A=”<<b;
return 0;
}
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 40

Nesting of if-else statements


#include<iostream.h> else
{
#include<conio.h>
cout<<"C ia largest among three numbers\n";
int main() }
{ }
int a,b,c; else
{if(b>c)
cout<<"Enter a,b,c values:";
{
cin>>a>>b>>c; cout<<"B ia largest among three numbers\n";
if(a>b) }
{ else
{
if(a>c)
cout<<"C ia largest among three numbers\n";
{ }
cout<<"A ia largest among three }
numbers\n“; getch();
} return 0;
}
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 41

THE SWITCH STATEMENT or


MULTIWAY SELECTION :
#include<iostream.h>
int main() case '-': cout<<"Difference : "<<(a -
{ b)<<endl;
float a,b; break;
char opr; case '*': cout<<”Product : "<<a *
cout<<"Enter number1 operator b<<endl;
number2 : "; break;
cin>>a>>oper>>b; case '/': cout<<”Quotient :"<<(a /
switch(opr) b)<<endl;
{ break;
case '+': default: cout<<”Invalid
cout<<"Sum : "<<(a + b)<<endl; Operation!"<<endl;
break; }
return 0;
}
Loop control statements or
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 42

repetitions:
 A block or group of statements executed repeatedly until some condition is
satisfied is called Loop.

 The group of statements enclosed within curly brace is called block or


compound statement.

We have two types of looping structures.

 One in which condition is tested before entering the statement block called
entry control.

 The other in which condition is checked at exit called exit controlled loop.
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 43

Loop statements can be divided into three categories as given below

1.while loop statement

2.do while loop statement

3.for loop statement


COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 44

1.WHILE STATEMENT :
It is an entry controlled loop. The condition is evaluated and if
it is true then body of loop is executed. After execution of body the
condition is once again evaluated and if is true body is executed once
again. This goes on until test condition becomes false.

Syntax

While(test condition)
{
body of the loop
}
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 45

Program
#include<iostream.h>
int main()
{
int i = 1,sum = 0,n;
cout<<"Enter N"<<end;
cin>>n;
while(i<=n)
{
sum = sum + i;
i = i + 1;
}
cout<<”Sum of first”<<n<”natural numbers
is:”<<sum<<endl;
return 0;
}
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 46

DO WHILE STATEMENT
The while loop does not allow body to be executed if test condition is false. The
do while is an exit controlled loop and its body is executed at least once.

Syntax:

do
{
body
}while(test condition);
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 47

Program
#include<iostream.h>
int main()
{
Int i = 1,sum = 0,n;
cout<<”Enter N"<<endl;
cin>>n
do{
sum = sum + i;
i = i + 1;
} while(i<=n);
cout<<”Sum of first”<< n<<” natural numbers is:”<<sum;
return 0;
}
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 48

FOR LOOP :
It is also an entry control loop that provides a more concise structure.
For statement is divided into three expressions each is separated by
semicolon;

1. initilization expression is used to initialize variables

2. test expression is responsible of continuing the loop. If it is true, then the


program control flow goes inside the loop and executes the block of
statements associated with it .If test expression is false loop terminates.

3. increment/decrement expression consists of increment or decrement


operator This process continues until test condition satisfies.
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 49

Program
#include<iostream.h>
int main()
{
Int i ,sum = 0,n;
cout<<”Enter N";
cin>>n;
for(i=1;i<=n;i++)
{
sum = sum + i;
}
cout<<“Sum of first”<<n<<” natural numbers is:%d”<<sum;
return 0;
}
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 50

Unconditional control statements:


Statements that transfers control from on part of the program to another part
Unconditionally. Different unconditional statements are

1)Goto

2)Break

3)Continue
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 51

Goto:
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 52

Program
#include<iostream.h>
int main()
{
int i ,sum = 0,n;
cout<<”Enter N";
cin>>n;
i=1;
Lable1:
sum = sum + i;
i++;
if(i<=n)
goto Lable1;
cout<<“Sum of first “<<n<” natural numbers is”<<sum;
return 0;
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 53

break:-

when a break statement is encountered within a


loop ,loop is immediately exited and the program
continues with the statements immediately following
loop.
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 54

Program
#include<iostream.h>
void main ()
{
int i;
for(i = 0; i<10; i++)
{
cout<<i;
if(i == 5)
break;
}
cout<<i;
getch();

}
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 55

Continue:

It is used to continue the iteration of the loop statement


by skipping the statements after continue statement. It
causes the control to go directly to the test condition
and then to continue the loop.
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 56

Program
#include<iostream.h>
int main()
{
for (int j=0; j<=8; j++)
{
if (j==4)
{
continue;
}
cout<<j;
}
return 0;
}
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 57

class
It is a collection of data and member functions that
manipulate data. The data components of class are
called data members and functions that manipulate
the data are called member functions. It can also
called as blue print or prototype that defines the
variables and functions common to all objects of
certain kind. It is also known as user defined data type
or ADT(abstract data type) A classis declared by the
keyword class
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 58

Syntax:-
class class_name
{
Access specifier :

Variable declarations;

Access specifier :

function declarations;
};
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 59

Access Control:
Access specifier or access modifiers are the labels that
specify type of access given to members of a class. These
are used for data hiding. These are also called as visibility
modes. There are three types of access specifiers

1.private
2.public
3.protected
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 60

1.Private: If the data members are declared as private access


then they cannot be accessed from other functions outside the
class. It can only be accessed by the functions declared within
the class. It is declared by the key word “private‟ .

2.public: If the data members are declared public access then


they can be accessed from other functions out side the class. It
is declared by the key word “public‟ .

3.protected: The access level of protected declaration lies


between public and private. This access specifier is used at
the time of inheritance
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 61

Program
#include<iostream.h> void putdata()
class student {
{ cout<<”Roll no:”<<roll<<endl;
private: cout<<Name:”<<name<<endl;
int roll; }
char name[20]; };
public: int main()
void getdata() {
{ student s;
cout<<”Enter Roll number:”; s.getdata();
cin>>roll; s.putdata();
cout<<”Enter Name:”; returm 0;
cin>>name; }
}
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 62

Scope Resolution operator:


#include <iostream.h>
class sample
{
public:
void output(); //function declaration
};
// function definition outside the class
void sample::output() {
cout << "Function defined outside the class.\n";
};
int main() {
sample obj;
obj.output();
return 0;
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 63

Write a program to find area of rectangle


#include<iostream.h> int rectangle::area()
class rectangle {
{ return L*B;
int L,B; }
public: int main()
void get_data(); {
void area(); rectangle r;
}; r.get_data();
void rectangle::get_data() cout<<”Area of rectangle is”<<r.area();
{ return 0;
cout<<”Enter Length of rectangle”; }
cin>>L;
cout<<”Enter breadth of rectangle”;
cin>>B;
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 64

INLINE FUNCTIONS:
An inline function is a function that is expanded in line when it is
invoked. Inline expansion makes a program run faster because
the overhead of a function call and return is eliminated. It is
defined by using key word “inline”.

General Form:

inline function-header
{

function body;
}
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 65

Necessity of Inline Function:


1. One of the objectives of using functions in a program is to save some memory
space, which becomes appreciable when a function is likely to be called many
times.

2. Every time a function is called, it takes a lot of extra time in executing a series of
instructions for tasks such as jumping to the function, saving registers, pushing
arguments into the stack, and returning to the calling function.

3. When a function is small, a substantial percentage of execution time may be spent in


such overheads. One solution to this problem is to use macro definitions, known as
macros. Preprocessor macros are popular in C. The major drawback with macros is
that they are not really functions and therefore, the usual error checking does not
occur during compilation.

4. C++ has different solution to this problem. To eliminate the cost of calls to small
functions, C++ proposes a new feature called inline function.
Situations where inline does not
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 66

work:
1. A function that is returning value , if it contains
switch ,loop or both then it is treated as normal
function.
2. if a function is not returning any value and it contains
a return statement then it is treated as normal
function
3. If function contains static variables then it is executed
as normal function
4. If the inline function is declared as recursive function
then it is executed as normal function
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 67

Program
#include<iostream.h> int main()
inline float mul(float x, float y)
{
{
return (x*y);
float a=12.345;
} float b=9.82;
inline double div(double p, cout<<mul(a,b);
double q) cout<<div(a,b);
{
return 0;
return (p/q);
}
}
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 68

STATIC CLASS MEMBERS

 Static Data Members

 Static Member Functions


COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 69

Static Data Members:


A data member of a class can be qualified as static. A static member
variable has certain special characteristics:

1. It is initialized to zero when the first object of its class is created. No


other initialization is permitted.

2. 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.

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

4. Static data member is defined by keyword “static‟


COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 70

Syntax:

Data type class name :: static_variable Name;

Ex: int item :: count;


COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 71

Program
class X
{
public:
static int i;
};
int X::i=1;
int main()
{
X obj;
cout << obj.i;
return 0;
}
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 72

Static Member Functions


Like static member variable, we can also have static
member functions. A member function that is declared
static has the following properties:

 A static function can have access to only other static


members (functions or variables) declared in the same
class.

 A static member function is to be called using the


class name (instead of its objects) as follows:
class-name :: function-name;
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 73

Program
#include<iostream.h>
class student
{
public:
static void printMsg()
{
cout<<"Welcome ";
}
};
int main()
{
student::printMsg();
}
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 74

Arrays of Objects:
 Arrays of variables of type "class" is known as "Array of objects". An array of
objects is stored inside the memory in the same way as in an ordinary array.

Syntax:
class class_name
{
private:
data_type members;
public:
data_type members;
member functions;
};
Class_name object_name[size];
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 75

Program
#include<iostream.h> void main()
class MyClass {
{
MyClass obj[5];
int a;
public: for(int i=0;i<5;i++)
void set(int x) obj[i].set(i);
{ for(int i=0;i<5;i++)
a=x; cout<<obj[i].get();
}
getch();
int get()
{ }
return a;
}
};
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 76

Reference variable
A reference variable is an alias, that is, another name for an
already existing variable and it is created with the & operator.
Reference to a variable provides alternate name for previously
defined variable. If any change made to reference variable then
there is a change to original variable.
A reference variable can be declared as follows:
Syntax:

Datatype & reference variable =variable;


Ex:
int x=5;
int &y=x;
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 77

Program
#include <iostream.h> i = 5;
int main () cout << "Value of i : " << i;
{ cout << r ;
int i; d = 11.7;
double d; cout << "Value of d :"<< d;
int & r = i; cout << s ;
double & s = d; return 0;
}
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 78

Reference variable
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 79

Constructor
A constructor is a special member function whose task is to initialize
the objects of its class. It is special because its name is the
same name as the class name. The constructor is invoked
whenever an object of its associated class is created. It is called
constructor because it constructs the values of data members of
the class. In other words A constructor in C++ is a special
method that is automatically called when an object of a class is
created.
CHARACTERISTICS OF
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 80

CONSTRUCTOR
1. They should be declared in the public section.
2. They are invoked automatically when the objects are created.
3. They do not have return type, not even void.
4. They cannot be inherited, though a derived class can call the
base class constructor.
5. Like other c++ functions, they can have default arguments.
6. Constructors cannot be virtual.
7. We cannot refer to their addresses.
8. They make “implicit calls‟ to the operators new and delete
when memory allocation is required.
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 81

Types of constructor

Constructors are of 3 types:

1. Default Constructor
2. Parameterized Constructor
3. Copy Constructor
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 82

1.Default Constructor:

A constructor that accepts no parameters is called the


default constructor.
In other words A default constructor doesn’t have any
arguments (or parameters)
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 83

Program
#include <iostream.h> int main(void)
class Website {
{ Website obj1;
public: Website obj2;
Website() return 0;
{ }
cout<<"Welcome "<<endl;
}
};
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 84

Parameterized Constructors:-

The constructors that take parameters are called parameterized constructors.


COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 85

Program
#include <iostream.h> int main(void)
class Add {
{ Add obj1(10, 20); //implicit call
public: Add obj2 = Add(50,
60);//explicit call
Add(int num1, int num2) return 0;
}
{ cout<<(num1+num2)<
<endl;
}
};
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 86

Copy Constructor
 A copy constructor is used to declare and initialize an object from another
object. Copy Constructor is a type of constructor which is used to create a
copy of an already existing object of a class type.
Eg:

item t2(t1);
or
item t2=t1;
Syntax of Copy Constructor
Classname(const classname & objectname)
{

}
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 87

Program
#include<iostream.h> void display()
class Sample {
{ cout<<x<<" "<<y<<endl;
private: int x, y; }
public: };
Sample(int x1, int y1) int main()
{ x = x1; {
y = y1; Sample obj1(10, 15);
} Sample obj2 = obj1;
Sample (const Sample&sam) { obj1.display();
x = sam.x; obj2.display();
y = sam.y; return 0;
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 88

Another program
class sample void display()
{ {
int n; cout<<n;
}
public: };
sample() void main()
{
{
n=0;
sample A(100);
}
sample B(A);
sample(int a)
sample C=A;
{
n=a; sample D;
} D=A;
sample(sample &x) A.display();
{ B.display();
n=x.n; C.display();
} D.display();}
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 89

DESTRUCTORS:
A destructor, is used to destroy the objects that have been created by a
constructor. Like a constructor, the destructor is a member function whose
name is the same as the class name but is preceded by a tilde.
Eg: ~item() { }

1. A destructor never takes any argument nor does it return any value.

2. It will be invoked implicitly by the compiler upon exit from the program to
clean up storage that is no longer accessible.

3. It is a good practice to declare destructors in a program since it releases


memory space for future use.
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 90

Program
#include<iostream.h> ~Marks() {
class Marks cout << "Inside "<<endl;
{ cout << "C++ "<<endl;
public: }
int maths; };
int science; int main( )
Marks() {
{ Marks m1;
cout << "Inside"<<endl; Marks m2;
cout << "C++ "<<endl; return 0;
} }
C++ Overloading
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 91

When we create two or more members of a class having the same name but
different in number or type of parameters, it is known as C++ overloading. In
C++, we can overload:

 methods,
 constructors, and
 operator
Types of overloading in C++
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 92
Function overloading
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 93

 Function Overloading in C++ can be defined as the process of


having two or more member functions of a class with the same
name, but different in parameters. In function overloading, the
function can be redefined either by using different types of
arguments or a different number of arguments according to the
requirement. It is only through these differences compiler can
differentiate between the two overloaded functions.

 One of the major advantages of Function overloading is that it


increases the readability of the program because we don’t need
to use different names for the same action again and again.
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 94

Advantages of function
Overloading in C++
 We use function overloading to save the memory space, consistency, and
readability of our program.

 With the use function overloading concept, we can develop more than one
function with the same name

 Function overloading shows the behavior of polymorphism that allows us


to get different behavior, although there will be some link using the same
name of the function.

 Function overloading speeds up the execution of the program.


 Function overloading is used for code reusability and also to save memory.
 It helps application to load the class method based on the type of
parameter.
 Code maintenance is easy.
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 95
By changing the Number of Arguments

In this way of function overloading, we define two


functions with the same names but a different number
of parameters of the same type.
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 96

Program
#include <iostream> int main()
int add(int a, int b) {
{
cout << a+b <<endl; add(20, 40);
return 0;
} add(40, 20, 30);
int add(int a, int b, int c) }
{
cout << a+b+c <<endl;
return 0;
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 97
By having different types of Arguments

In this method, we define two or more functions


with the same name and the same number of
parameters, but the data type used for these
parameters are different.
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 98

Program
#include <iostream.h> int main()
int add(int x, int y) {
{ add(20, 40);
cout<< x+y << endl; add(23.45f, 34.5f);
return 0; add(40.24, 20.433);
}
float add(float a, float b) }
{
cout << a+b << endl;
return 0;
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 99
Disadvantages of function Overloading in C++

 Function declarations that differ only by its return type cannot be overloaded
with function overloading process.

 Member function declarations with the same parameters or the same name
types cannot be overloaded if any one of them is declared as a static
member function.
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 100
Function Overloading and Ambiguity

When the compiler is unable to decide which function it should invoke first
among the overloaded functions, this situation is known as function
overloading ambiguity. The compiler does not run the program if it shows
ambiguity error. Causes of Function Overloading ambiguity:

 Type Conversion.
 Function with default arguments.
 Function with a pass by reference
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 101

Type Conversion:
#include<iostream.h> int main()
void function(float); {
void function(int);
function(3.4);
void function(float x)
{
function(34);
std::cout << "Value of x is : " return 0;
<<x<< std::endl; }
}
void function(int y)
{
std::cout << "Value of y is : "
<<y<< std::endl;
Function with Default
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 102

Arguments:
#include<iostream.h>
void function(int);
int main()
void function(int,int); {
void function(int x) function(12);
{
std::cout << "Value of x is : " <<x<< return 0;
std::endl; }
}
void function(int y, int z=12)
{
std::cout << "Value of y is : " <<y<<
std::endl;
std::cout << "Value of z is : " <<z<<
std::endl;
}
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 103

Function with pass by reference


#include <iostream.h> int main()
void function(int); {
void function(int &);
int x=10;
void function(int a)
{
function(x);
std::cout << "Value of a is : " return 0;
<<a<< std::endl; }
}
void function(int &b)
{
std::cout << "Value of b is : "
<<b<< std::endl;
Constructor Overloading
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 104

In C++, We can have more than one constructor in the class with the same
name, as long as each has a different list of arguments. This concept is
known as Constructor Overloading and is quite similar to
function overloading.
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 105

Program
#include <iostream.h> ABC(int a , int b)
{
class ABC
x = a; y = b;
{ }
private: void display()
int x,y; {
cout << "x = " << x << " and " << "y = " << y <<
public: endl; }
ABC () };
{ int main()
x = y = 0; {
ABC cc1;
} ABC cc2(10);
ABC(int a) ABC cc3(10,20);
{ cc1.display();
x = y = a; cc2.display();
cc3.display();
} return 0;
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 106

OPERATOR OVERLOADING
 C++ has the ability to provide the operators with as special meaning for a
data type. The mechanism of giving such special meanings to an operator is
known as operator overloading. Operator overloading is a compile-time
polymorphism in which the operator is overloaded to provide the special
meaning to the user-defined data type. Operator overloading provides a
simple and easy way for the development of new definitions for most of the
operators in C++.
Operator that cannot be overloaded are as follows:

1. Scope operator (::)


2. Sizeof
3. member selector(.)
4. member pointer selector(*)
5. ternary operator(?:)
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 107

Syntax of Operator Overloading

return_type class_name : : operator op(argument_list)


{
// body of the function.
}
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 108

Rules for Operator Overloading


 Existing operators can only be overloaded, but the new operators cannot be
overloaded.
 The overloaded operator contains atleast one operand of the user-defined
data type.
 We cannot use friend function to overload certain operators. However, the
member function can be used to overload those operators.
 When unary operators are overloaded through a member function take no
explicit arguments, but, if they are overloaded by a friend function, takes one
argument.
 When binary operators are overloaded through a member function takes
one explicit argument, and if they are overloaded through a friend function
takes two explicit arguments.
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 109

Types of overloading approaches

Operator Overloading can be done by using 2 approaches, they are

 Overloading unary operator.

 Overloading binary operator.


COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 110

Binary Operator Overloading


An binary operator means, an operator which works on two operands. For
example, + is an binary operator, it takes single operand (c+d). So, when
overloading an binary operator, it takes one argument (one is object itself
and other one is passed argument).

Syntax for Binary Operator (Inside a class)

return-type operator operatorsymbol(argument)


{
//body of the function
}
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 111

program
#include <iostream.h> Height operator+(Height& d2)
{
class Height
Height h3;
{
h3.feet = feet + d2.feet;
public: h3.inch = inch + d2.inch;
int feet, inch; return h3;
Height() }
{ };
feet = 0; int main()
inch = 0; {
} Height h1(3, 7);
Height h2(6, 1);
Height(int f, int i)
Height h3;
{
h3 = h1 + h2;
feet = f; cout << "Sum of Feet & Inches: " <<
inch = i; h3.feet << "'" << h3.inch << endl;
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 112

Unary Operator Overloading


An unary operator means, an operator which works on single operand. For
example, ++ is an unary operator, it takess single operand (c++). So, when
overloading an unary operator, it takes no argument (because object itself is
considered as argument).

Syntax for Unary Operator (Inside a class)

return-type operator operatorsymbol( )


{
//body of the function
}
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 113

Program
#include <iostream.h> void operator-()
class Height { {
public: feet--;
int feet, inch; inch--;
Height(int f, int i) cout << "Feet & Inches after decrement: " << feet
{ << " ' " << inch <<endl;
feet = f; }
inch = i; };
} int main()
{
Height h1(6, 2);
-h1;
return 0;
}
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 114

FRIEND FUNCTIONS:
The private members cannot be accessed from outside the class. i.e.… a non
member function cannot have an access to the private data of a class. In C++ a
non member function can access private by making the function friendly to a
class.
Definition:

A friend function is a function which is declared within a class and is defined


outside the class. It does not require any scope resolution operator for
defining . It can access private members of a class. It is declared by using
keyword “friend”
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 115

Program
class sample int sum(sample s)
{ {
int x,y; int sum;
public: sum=s.x+s.y;
sample(int a,int b); return 0;
friend int sum(sample s); }
}; void main()
sample::sample(int a,int b) {
{ Sample obj(2,3);
x=a;y=b; int res=sum(obj);
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 116

Inheritance in C++
 The mechanism of deriving a class from another class is known
as Inheritance.

 Inheritance is the most importance concept of object oriented


programming.

 It allows us to define a class in terms of another class, which


helps to create and maintain an application.

 The main advantage of Inheritance is, it provides an


opportunity to reuse the code functionality and fast
implementation time.

 The members of the class can be Public, Private or


COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 117

Syntax:
class DerivedClass : AccessSpecifier BaseClass

1. The default access specifier is Private.


2. Inheritance helps user to create a new class (derived
class) from a existing class (base class).
3. Derived class inherits all the features from a Base class
including additional feature of its own.
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 118

Types of Inheritance.

1. Single Inheritance

2. Multiple Inheritance

3. Multilevel Inheritance

4. Hierarchical Inheritance

5. Hybrid Inheritance
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 119

Single Inheritance
In Single Inheritance, one class is derived from another class.
It represents a form of inheritance where there is only one base and
derived class.
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 120

C++ program to explain Single


inheritance
#include <iostream.h>
Class
Vehicle
{ public:
Vehicle()
{
cout <<
"This is a
Vehicle"
<< endl;
}
};
class Car:
public
Vehicle{
};
int main()
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 121

Multiple Inheritance:

Multiple Inheritance is a feature of C++ where a class can inherit from


more than one classes. i.e one sub class is inherited from more
than one base classes.
Syntax
class subclass_name : access_mode base_class1, access_mode base_class2,

{ //body of subclass
};
C++ program to explain
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 122

multiple inheritance
#include <iostream.h> class Car: public Vehicle, public
FourWheeler
Class Vehicle{
{
public:
Vehicle()
};
{
int main()
cout << "This is a Vehicle" << endl;
{
}
Car obj;
};
return 0;
class FourWheeler {
}
public:
FourWheeler()
{
cout << "This is a 4 wheeler Vehicle“;
}
};
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 123

3.Multilevel Inheritance
In this type of inheritance, a derived class is created from another
derived class.
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 124

Program
class Vehicle class Car: public fourWheeler
{ {
public: public:
Vehicle()
car()
{
{
cout << "This is a Vehicle" << endl;
} cout<<"Car has 4
}; Wheels"<<endl;
class fourWheeler: public Vehicle }
{ public: };
fourWheeler()
{ int main()
cout<<"Objects with 4 wheels are {
vehicles"<<endl;
} Car obj;
}; return 0;
}
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 125

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.
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 126

Program
#include <iostream> int main()
class Vehicle {
{ Car obj1; Bus obj2;
public:
return 0;
Vehicle()
{ }
cout << "This is a Vehicle" << endl;
}
};
class Car: public Vehicle
{

};
class Bus: public Vehicle
{

};
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 127

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:
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 128

Program
#include <iostream.h> class Car: public Vehicle
class Vehicle
{
{
};
public:
Vehicle()
class Bus: public Vehicle, public Fare
{ {
cout << "This is a Vehicle"
<< endl; };
}
};
class Fare int main()
{ {
public: Bus obj2;
Fare() return 0;
{cout<<"Fare of Vehicle\n";
}
}
};
Function Overriding
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 129

If derived class defines same function as defined in its base class, it is known
as function overriding in C++. It is used to achieve runtime polymorphism.
It enables you to provide specific implementation of the function which is
already provided by its base class.
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 130

Program
#include <iostream.h> int main()
class Animal { {
public: Dog d = Dog();
void eat(){
d.eat();
cout<<"Eating...";
} return 0;
}; }
class Dog: public Animal
{
public:
void eat()
{
cout<<"Eating bread...";
}
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 131

Virtual function

A virtual function is a member function which is declared within a base class


and is re-defined(Overriden) 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.
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 132

Rules for Virtual Functions


 Virtual functions cannot be static and also cannot be a friend function of
another class.

 Virtual functions should be accessed using pointer or reference of base


class type to achieve run time polymorphism.

 The prototype of virtual functions should be same in base as well as


derived class.

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

 A class may have virtual destructor but it cannot have a virtual constructor.
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 133

More points

 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 Run-time.


COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 134

Program
#include <iostream> class derived : public base {
public:
class base { void print()
public: {
cout << "print derived class" << endl;
virtual void print() }
{
void show()
cout << "print base class" <<
{
endl; cout << "show derived class" << endl;
} }
};

void show() int main()


{
{
base* bptr;
cout << "show base class" << derived d;
endl; bptr = &d;
bptr->print();
}
bptr->show();
}; }
this Pointer
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 135

In C++ programming, this is a keyword that refers to the current instance of the
class. There can be 3 main usage of this keyword in C++.

 It can be used to pass current object as a parameter to another method.

 It can be used to refer current class instance variable.

 It can be used to declare indexers.


COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 136

Program
#include <iostream.h> int main()
class Employee { {
public: Employee e1 =Employee(101, "Sonoo", 890000);
int id; Employee e2=Employee(102, "Nakul", 59000);
string name; e1.display();
float salary; e2.display();
Employee(int id, string name, float salary) return 0;
{ }
this->id = id;
this->name = name;
this->salary = salary;
}
void display()
{
cout<<id<<" "<<name<<" "<<salary<<endl;

}
};
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 137

The diamond problem


The diamond problem occurs when two superclasses of a class have a
common base class. For example, in the following diagram, the TA class
gets two copies of all attributes of Person class, this causes ambiguities.
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 138

Program
#include<iostream>
class Person { class Student : public Person {
public: public:
Person(int x) Student(int x):Person(x) {
{ cout<<"Student::Student(int ) called"<<
cout << "Person::Person(int ) called" << endl; endl;
} }
}; };

class Faculty : public Person { class TA : public Faculty, public Student {


public: public:
Faculty(int x):Person(x) { TA(int x):Student(x), Faculty(x) {
cout<<"Faculty::Faculty(int ) called"<< cout<<"TA::TA(int ) called"<< endl;
endl; }
} };
}; int main() {
TA ta1(30);
}
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 139

Virtual base class


#include<iostream.h> class Student : virtual public Person {
class Person { public:
public: Student(int x):Person(x) {
Person(int x) { cout << cout<<"Student::Student(int )
"Person::Person(int ) called" << endl; called"<< endl;
}
}
Person() { cout << "Person::Person()
};
called" << endl; }
class TA : public Faculty, public Student {
};
public:
TA(int x):Student(x), Faculty(x) {
class Faculty : virtual public Person {
cout<<"TA::TA(int ) called"<< endl;
public:
}
Faculty(int x):Person(x) {
};
cout<<"Faculty::Faculty(int )
called"<< endl; int main() {
} TA ta1(30);
}; }
Dynamic Memory Allocation
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 140

 C language uses ‘malloc’,’calloc’ and ‘realloc’ functions to allocate memory


dynamically. To de-allocate the memory allocated dynamically with these
functions, it uses ‘free’ function call. C++ language also supports these
functions from the C language to allocate/de-allocate memory.

 Apart from these functions, C++ introduces two new operators which are
more efficient to manage the dynamic memory. These are ‘new’ operator for
allocating memory and ‘delete’ operator for de-allocating memory.
The “new” Operator
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 141

The “new” operator allocates memory for a variable or any other entity on a
heap.

The general syntax of the “new” operator is:

pointer_variable_of_data_type = new data type;

The data type mentioned above can be any valid data type supported by C++.
It can be a built-in datatype or any user-defined data type including classes
and structures.
The Delete Operator
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 142

The memory allocated dynamically using the new operator has to be freed
explicitly by the programmer. For this purpose, we are provided with the
“delete” operator.
The general syntax of the delete operator is:

delete pointer_variable;

So we can free the memory allocated to the ptr variable above as follows:

delete ptr;

This statement frees the memory allocated to the variable “ptr” back to the
memory pool.
COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 143

Program
#include<iostream.h> for(i=0;i<5;i++)
#include<conio.h> {
void main() cout<<"\nEnter any number : ";
{ cin>>ptr[i];
int size,i; }
int *ptr; for(i=0;i<5;i++)
cout<<"\n\tEnter size of Array : "; cout<<ptr[i]<<", ";
cin>>size; delete[] ptr;
ptr = new int[size]; }
THANK YOU

You might also like