SlideShare a Scribd company logo
1 of 40
1
The C++ Language
• C Evolves into C++
• Object Oriented Programming
– Classes and Objects
– Operator Overloading
– Inheritance
– Polymorphism
– Template classes
2
C Evolves into C++
3
C is Alive in C++
• C++ is a superset of C.
• Any correct C program is also a correct C+
+ program, except for some loopholes in C
that are not allowed in C++.
4
What is still the same
• The syntax of statements
if-else, switch, the “?:” conditional
for/while/do-while loops
assignments
arithmetic/logic/relational/ bitwise expressions
declarations, struct/union/enum types, typedef
pointers, arrays,
casting
• Same preprocessor commands in C &C++.
5
C++: A Better C
• Convenient syntax for inline comments: // …
• Declaration anywhere
• Function overloading
• Default arguments
• Simplified IO: cin >>, cout<<, and more
• A new Boolean data type: bool
• Easier dynamic memory allocation: new & delete
• References (automatically dereferenced pointers)
• Function templates: data types as parameters
• Tag names as new data types
• Better type system: tighter use of void *
6
Convenient Syntax for Inline
Comments
• Anything from // to the end of line is
considered a comment and thus ignored by
the compiler.
• The C-syntax for comments, /* … */, can
still be used for multi-tine comments.
int i; // i is an integer that will index the next array
double x[10]; // an array that will store user input
// and will then be sorted.
7
Declaration Anywhere
• Declarations need no longer be at the head
of blocks.
• Variables and functions can be declared any
time, anywhere in a program, preferably as
close to where a variable is used the first
time.
• For example: note i is declared within for
for (int i=0;i<n;i++)
8
Function Overloading
• Two or more functions can have the same
name but different parameters
• Example:
int max(int a, int b) {
if (a>= b)
return a;
else
return b;
}
float max(float a, float b) {
if (a>= b)
return a;
else
return b;
}
9
Default Arguments
• A default argument is a value given in the
function declaration that the compiler
automatically inserts if the caller does not
provide a value for that argument in the
function call.
• Syntax:
return_type f(…, type x = default_value,…);
10
Default Arguments
(Examples)
• The default value of the 2nd
argument is 2.
• This means that if the programmer calls
pow(x), the compiler will replace that call
with pow(x,2), returning x2
double pow(double x, int n=2)
// computes and returns xn
11
Default Arguments
(Rules)
• Once an argument has a default value, all
the arguments after it must have default
values.
• Once an argument is defaulted in a
function call, all the remaining arguments
must be defaulted.
int f(int x, int y=0, int n)
// illegal
int f(int x, int y=0, int n=1)
// legal
12
Examples of Legal/Illegal Defaulting
in Function Calls
• Let substring be a function whose prototype is:
• Assume
• Which call to substring is OK and which is not
OK? If OK, what is it equivalent to?
– substring(p)
– substring(p,10)
– substring( )
char * substring (char *p, int length=10, int pos=0)
char *p=“hello”;
13
Default Arguments and
Function Overloading
• Default arguments and function overloading
can give rise to an ambiguity
• Consider an overloaded function f where
one declaration has default arguments that,
if removed, makes the function look
identical to a second declaration, as in
1. int f(int x, int y=0); returns xy
2. int f(int x); // returns 2x
If we call f(2), is it to f
in (1) or (2)?
The 1st
returns 1.
The 2nd
returns 4.
14
Default Arguments and
Function Overloading (Contd.)
• If overloaded declarations of a function
with default arguments cause ambiguity, the
compiler gives an error message.
• It is the responsibility of the programmer
not to cause such ambiguities.
15
Example of Function
Overloading and Default Args
// Precondition: x[] is a double array of length n.
// n is a positive integer. If missing, it defaults to 10
// Postcondition: the output is the maximum in x[]
double max(double x[], int n=10){
double M = x[0]; // M is the maximum so far
for (int i=1;i<n;i++)
if (x[i]>M)
M=x[i];
return M;
}
16
Overloading & Defaulting Example (Contd.)
// Precondition: x[] is an int array of length n.
// n is a positive integer. If missing, it defaults to 10
// Postcondition: the output is the maximum in x[]
int max(int x[], int n=10){
int M = x[0]; // M is the maximum so far
for (int i=1;i<n;i++)
if (x[i]>M)
M=x[i];
return M;
}
17
Simplified IO
• Instead of the complicated syntax of printf and
scanf, and the many variations of print and scan,
C++ offers a much simpler syntax
• For standard output, use cout
• For standard input, use cin
• File IO is also simpler, and will be discussed later
• Note: one can still use the IO syntax of C in C++
18
Cout
• For printing output, use this syntax:
This prints out the string or the value of the
extpression.
• For output chaining, use this syntax
Each Si is a string or an expression. The effect is to
print out the value of S1 followed by the value of
S2, followed by the value of S3.
cout << a string or an expression;
cout << S1 <<S2<<S3<<endl;
19
Cout (Contd.)
• The reserved word, endl, ensures that the
next cout command prints its stuff on a new
line.
• New lines can also be added using “n”.
20
Cout (Examples)
Statements Output
int x=3; double y =4.5;
cout <<“the value of x=“<<x;
cout<<“; y=“<<y<<endl;
cout <<“x+y”<<x+y;
the value of x=3; y=4.5
x+y=7.5
int x=3; double y =4.5;
cout <<“x = “<<x<<“n”;
cout<<“y=“<<y;
cout <<“nx+y”<<x+y;
x = 3
y=4.5
x+y=7.5
21
Cin
• For reading input values into variables:
• This reads the input from the standard input
(say the screen for now), puts the first read
value in variableName1, the second read
value in variableName2, and the third read
value in variableName3.
cin >> variableName1 >> variableName2 >> variableName3;
22
Cin (Examples)
• Suppose you want to read an int value and a
double value into variables n and x.
• This code will do it (see next slide):
int n; double x;
cout<<“enter an int, a space, and a double: “;
cin>>n>>x; // use of cin
cout<<“You entered int n=“<<n;
cout<<“, and double x=“<<x<<endl;
23
• If you run that code, you first get:
• Let’s say, you enter: -3 9.8
• The code next will store –3 in n, and 9.8 in
x, and print out to you:
Enter an int, a space, and a double:
Enter an int, a space, and a double: -3 9.8
You entered int n=-3, and double y=9.8
24
A new Boolean data type:
bool
• A bool variable is a variable that can have
only two values: true or false.
• C does not have Boolean values or variables
• Instead, any non-zero was considered the
equivalent of true , and 0 the equivalent of
false.
25
Example of bool
// Precondition: x[] is an integer array of length n.
// n is a positive integer.
// Postcondition: The output is true if the elements
// of the input array are all positive,. Else, false.
bool isAllPositive(int x[], int n){
for(int i=0;i<n;i++)
if (x[i] <= 0)
return false;
return true;
}
26
A Comprehensive Example
#include <cstdlib>
#include <iostream>
using namespace std;
// codes for isAllPositive( ), and for overloaded
// function max( ) should be inserted here
int main(int argc, char *argv[]){
cout << " enter five integers :";
int x[5]; int n=5;
for (int i=0;i<n;i++) // read the input to x[]
cin>>x[i];
27
cout << "You entered: ";
for (int i=0;i<n;i++)
cout << x[i]<<" ";
if (isAllPositive(x,n))
cout << “nYour data is all positiven";
else
cout << “n Your data is not all positiven";
int M = max(x,n);
cout<<“Your maximum value is: "<<M<<endl;
} // end of main( )
28
Easier Dynamic Memory
Allocation: new & delete
• new corresponds to malloc/calloc in C
• delete corresponds to free in C
• The syntax of new has forms:
• The semantics of this syntax is explained next
–type *pointer = new type; // type is a built-in
// or user-defined data type.
–type *pointer = new type[n]; // type as above
29
Semantics of new
• For type *pointer = new type; :
– The system allocates dynamically (during
execution) a chunk of memory large enough to
hold data of the specified type, and returns a
pointer pointing to the address of that chunk.
This pointer is stored in the user-provided
pointer-variable pointer.
30
Semantics of new [n]
• For type *pointer = new type[n]; :
– The system allocates dynamically an array of n
memory chunks, each large enough to hold data of the
specified type, and returns a pointer pointing to the
address of that chunk.
– The difference between this type of arrays (called
dynamic arrays) and conventional arrays is that the size
of the latter is constant while the size of the former can
vary.
31
Example of new
// Precondition: n is a positive integer
// Postcondition: computes and prints out the first n
// elements of the Fibonacci sequence
void fibonacci(int n){
int *x = new int [n]; // creation of a dynamic array
x[0]=1; x[1]=1;
for (int i=2;i<n;i++)
x[i]=x[i-1]+x[i-2];
cout<<"The Fibonacci sequence of "<<n<<" values are:n";
for (int i=0;i<n;i++)
cout<<"x["<<i<<"]="<<x[i]<<endl;
}
32
Syntax and Semantics of delete
• The syntax of delete has two forms:
• The first releases the memory of the single
memory chunk pointed to by pointer
• The second releases the memory
allocated to the array pointed to by
pointer.
– delete pointer ;
– delete [] pointer ;
33
References
• A reference is an autmatically dereferenced
pointer
• Syntax of reference declaration:
• Semantics: refname becomes another name
(or alias) for variable. Any change to the
value of variable causes the same change to
refname, and vice versa.
Type& refname = variable;
34
Illustration of References
Statements Outcome
int x=17;
int& xref = x;
cout<<“x=“<<x<<endl;
cout<<“xref=“<<xref<<endl;
x=17
xref=17
x=x+5;
cout<<“x=“<<x<<endl;
cout<<“xref=“<<xref<<endl;
x=22
xref=22
xref = xref-10;
cout<<“x=“<<x<<endl;
cout<<“xref=“<<xref<<endl;
x=12
xref=12
35
References and Function Call by
Reference
void swap(int x, int y){
int tmp=x; x=y; y=tmp;
}
int x=5; int y=10;
swap(x,y);
cout<<x<<“, “<<y;
void swap(int& x, int& y){
int tmp=x; x=y; y=tmp;
}
int x=5; int y=10;
swap(x,y);
cout<<x<<“, “<<y;
Outcome:
5, 10 // no swap
Outcome:
10, 5 // it did swap
36
Templates of Functions
(Motivation)
• Functions are a great construct because they all the
programmer to specify fairly generic parameters
(variable arguments), and later call a function
multiple times with different argument values,
thus saving on programming effort
• It will be equally convenient and effort-saving if
one can specify generic types that can be
substituted with any actual type whenever a
function is called
37
Templates of Functions
(Purpose and Syntax)
• Templates provide that great convenience
• They make the data type/types of function
arguments and of the return value to be
“programmable”
• Syntax for declaring template function:
template<class type> function_declaration;
-Or-
template<typename type> function_declaration;
38
Templates of Functions (Example)
// Precondition: x[] is an array of length n, of
// a generic type. n is a positive integer.
// Postcondition: the output is the minimum in x[]
template<typename T> T min(T x[], int n){
T m = x[0]; // M is the minimum so far
for (int i=1;i<n;i++)
if (x[i]<m)
m=x[i];
return m;
}
39
How to Call a Function Template
• The syntax of calling a function template:
• Example:
functionName<an-actual-type>(parameter-list);
int x[]={11, 13, 5, 7, 4, 10};
double y[]={4.5, 7.13, 3, 17};
int minx = min<int>(x,6);
double miny=min<double>(y,4);
cout<<“the minimum of array x is: “<<minx<<endl;
cout<<“the minimum of array y is: “<<miny<<endl;
40
Templates with More than One
Generic Type
• Templates can have several generic types
• Syntax for their declaration:
• class can be replaced by typename.
template<class type1,class type2> funct_decl;

More Related Content

What's hot (20)

interface in c#
interface in c#interface in c#
interface in c#
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
 
Classes objects in java
Classes objects in javaClasses objects in java
Classes objects in java
 
C by balaguruswami - e.balagurusamy
C   by balaguruswami - e.balagurusamyC   by balaguruswami - e.balagurusamy
C by balaguruswami - e.balagurusamy
 
Polymorphism in C++
Polymorphism in C++Polymorphism in C++
Polymorphism in C++
 
Tokens in C++
Tokens in C++Tokens in C++
Tokens in C++
 
C# classes objects
C#  classes objectsC#  classes objects
C# classes objects
 
C++ Overview
C++ OverviewC++ Overview
C++ Overview
 
Oop c++class(final).ppt
Oop c++class(final).pptOop c++class(final).ppt
Oop c++class(final).ppt
 
Friend function
Friend functionFriend function
Friend function
 
Type casting
Type castingType casting
Type casting
 
Datatype in c++ unit 3 -topic 2
Datatype in c++ unit 3 -topic 2Datatype in c++ unit 3 -topic 2
Datatype in c++ unit 3 -topic 2
 
Static Data Members and Member Functions
Static Data Members and Member FunctionsStatic Data Members and Member Functions
Static Data Members and Member Functions
 
Java Tokens
Java  TokensJava  Tokens
Java Tokens
 
Pointers in c++
Pointers in c++Pointers in c++
Pointers in c++
 
Java program structure
Java program structureJava program structure
Java program structure
 
Constructors and Destructors
Constructors and DestructorsConstructors and Destructors
Constructors and Destructors
 
Function overloading
Function overloadingFunction overloading
Function overloading
 
Arrays in Java
Arrays in JavaArrays in Java
Arrays in Java
 
C++ presentation
C++ presentationC++ presentation
C++ presentation
 

Viewers also liked (20)

Basics of c++ Programming Language
Basics of c++ Programming LanguageBasics of c++ Programming Language
Basics of c++ Programming Language
 
Data types
Data typesData types
Data types
 
C++ OOPS Concept
C++ OOPS ConceptC++ OOPS Concept
C++ OOPS Concept
 
functions of C++
functions of C++functions of C++
functions of C++
 
Function in c
Function in cFunction in c
Function in c
 
C++ programming
C++ programmingC++ programming
C++ programming
 
Function in C program
Function in C programFunction in C program
Function in C program
 
Basics of C programming
Basics of C programmingBasics of C programming
Basics of C programming
 
Elements of programming
Elements of programmingElements of programming
Elements of programming
 
Chapter 2 basic element of programming
Chapter 2 basic element of programming Chapter 2 basic element of programming
Chapter 2 basic element of programming
 
C++ Function
C++ FunctionC++ Function
C++ Function
 
User defined data type
User defined data typeUser defined data type
User defined data type
 
C++ Programming
C++ ProgrammingC++ Programming
C++ Programming
 
IP Addressing and subnetting
IP Addressing and subnettingIP Addressing and subnetting
IP Addressing and subnetting
 
Data type
Data typeData type
Data type
 
Lecture 03 Software Risk Management
Lecture 03 Software Risk ManagementLecture 03 Software Risk Management
Lecture 03 Software Risk Management
 
Characteristics of Software
Characteristics of SoftwareCharacteristics of Software
Characteristics of Software
 
Array and string
Array and stringArray and string
Array and string
 
Parm
ParmParm
Parm
 
Bitwise operators
Bitwise operatorsBitwise operators
Bitwise operators
 

Similar to C++ Language

Similar to C++ Language (20)

C++ Functions.ppt
C++ Functions.pptC++ Functions.ppt
C++ Functions.ppt
 
Chapter 4
Chapter 4Chapter 4
Chapter 4
 
CPP Homework Help
CPP Homework HelpCPP Homework Help
CPP Homework Help
 
Lecture 4
Lecture 4Lecture 4
Lecture 4
 
C++ FUNCTIONS-1.pptx
C++ FUNCTIONS-1.pptxC++ FUNCTIONS-1.pptx
C++ FUNCTIONS-1.pptx
 
C++ FUNCTIONS-1.pptx
C++ FUNCTIONS-1.pptxC++ FUNCTIONS-1.pptx
C++ FUNCTIONS-1.pptx
 
2.overview of c++ ________lecture2
2.overview of c++  ________lecture22.overview of c++  ________lecture2
2.overview of c++ ________lecture2
 
Cs1123 8 functions
Cs1123 8 functionsCs1123 8 functions
Cs1123 8 functions
 
85ec7 session2 c++
85ec7 session2 c++85ec7 session2 c++
85ec7 session2 c++
 
functions
functionsfunctions
functions
 
12 computer science_notes_ch01_overview_of_cpp
12 computer science_notes_ch01_overview_of_cpp12 computer science_notes_ch01_overview_of_cpp
12 computer science_notes_ch01_overview_of_cpp
 
C++ lectures all chapters in one slide.pptx
C++ lectures all chapters in one slide.pptxC++ lectures all chapters in one slide.pptx
C++ lectures all chapters in one slide.pptx
 
03 function overloading
03 function overloading03 function overloading
03 function overloading
 
4th_Ed_Ch03.pdf
4th_Ed_Ch03.pdf4th_Ed_Ch03.pdf
4th_Ed_Ch03.pdf
 
Pro
ProPro
Pro
 
Lecture#6 functions in c++
Lecture#6 functions in c++Lecture#6 functions in c++
Lecture#6 functions in c++
 
16717 functions in C++
16717 functions in C++16717 functions in C++
16717 functions in C++
 
Functions in C++.pdf
Functions in C++.pdfFunctions in C++.pdf
Functions in C++.pdf
 
Classes function overloading
Classes function overloadingClasses function overloading
Classes function overloading
 
Review functions
Review functionsReview functions
Review functions
 

More from Syed Zaid Irshad

More from Syed Zaid Irshad (20)

Operating System.pdf
Operating System.pdfOperating System.pdf
Operating System.pdf
 
DBMS_Lab_Manual_&_Solution
DBMS_Lab_Manual_&_SolutionDBMS_Lab_Manual_&_Solution
DBMS_Lab_Manual_&_Solution
 
Data Structure and Algorithms.pptx
Data Structure and Algorithms.pptxData Structure and Algorithms.pptx
Data Structure and Algorithms.pptx
 
Design and Analysis of Algorithms.pptx
Design and Analysis of Algorithms.pptxDesign and Analysis of Algorithms.pptx
Design and Analysis of Algorithms.pptx
 
Professional Issues in Computing
Professional Issues in ComputingProfessional Issues in Computing
Professional Issues in Computing
 
Reduce course notes class xi
Reduce course notes class xiReduce course notes class xi
Reduce course notes class xi
 
Reduce course notes class xii
Reduce course notes class xiiReduce course notes class xii
Reduce course notes class xii
 
Introduction to Database
Introduction to DatabaseIntroduction to Database
Introduction to Database
 
C Language
C LanguageC Language
C Language
 
Flowchart
FlowchartFlowchart
Flowchart
 
Algorithm Pseudo
Algorithm PseudoAlgorithm Pseudo
Algorithm Pseudo
 
Computer Programming
Computer ProgrammingComputer Programming
Computer Programming
 
ICS 2nd Year Book Introduction
ICS 2nd Year Book IntroductionICS 2nd Year Book Introduction
ICS 2nd Year Book Introduction
 
Security, Copyright and the Law
Security, Copyright and the LawSecurity, Copyright and the Law
Security, Copyright and the Law
 
Computer Architecture
Computer ArchitectureComputer Architecture
Computer Architecture
 
Data Communication
Data CommunicationData Communication
Data Communication
 
Information Networks
Information NetworksInformation Networks
Information Networks
 
Basic Concept of Information Technology
Basic Concept of Information TechnologyBasic Concept of Information Technology
Basic Concept of Information Technology
 
Introduction to ICS 1st Year Book
Introduction to ICS 1st Year BookIntroduction to ICS 1st Year Book
Introduction to ICS 1st Year Book
 
Using the set operators
Using the set operatorsUsing the set operators
Using the set operators
 

Recently uploaded

Extrusion Processes and Their Limitations
Extrusion Processes and Their LimitationsExtrusion Processes and Their Limitations
Extrusion Processes and Their Limitations120cr0395
 
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130Suhani Kapoor
 
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)Suman Mia
 
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Dr.Costas Sachpazis
 
Coefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxCoefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxAsutosh Ranjan
 
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...ranjana rawat
 
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Christo Ananth
 
main PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidmain PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidNikhilNagaraju
 
chaitra-1.pptx fake news detection using machine learning
chaitra-1.pptx  fake news detection using machine learningchaitra-1.pptx  fake news detection using machine learning
chaitra-1.pptx fake news detection using machine learningmisbanausheenparvam
 
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130Suhani Kapoor
 
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝soniya singh
 
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCollege Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCall Girls in Nagpur High Profile
 
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...srsj9000
 

Recently uploaded (20)

★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
 
Extrusion Processes and Their Limitations
Extrusion Processes and Their LimitationsExtrusion Processes and Their Limitations
Extrusion Processes and Their Limitations
 
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
 
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)
 
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
 
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
 
Coefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxCoefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptx
 
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
 
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
 
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptxExploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
 
Roadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and RoutesRoadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and Routes
 
main PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidmain PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfid
 
chaitra-1.pptx fake news detection using machine learning
chaitra-1.pptx  fake news detection using machine learningchaitra-1.pptx  fake news detection using machine learning
chaitra-1.pptx fake news detection using machine learning
 
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
 
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
 
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCRCall Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
 
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCollege Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
 
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
 

C++ Language

  • 1. 1 The C++ Language • C Evolves into C++ • Object Oriented Programming – Classes and Objects – Operator Overloading – Inheritance – Polymorphism – Template classes
  • 3. 3 C is Alive in C++ • C++ is a superset of C. • Any correct C program is also a correct C+ + program, except for some loopholes in C that are not allowed in C++.
  • 4. 4 What is still the same • The syntax of statements if-else, switch, the “?:” conditional for/while/do-while loops assignments arithmetic/logic/relational/ bitwise expressions declarations, struct/union/enum types, typedef pointers, arrays, casting • Same preprocessor commands in C &C++.
  • 5. 5 C++: A Better C • Convenient syntax for inline comments: // … • Declaration anywhere • Function overloading • Default arguments • Simplified IO: cin >>, cout<<, and more • A new Boolean data type: bool • Easier dynamic memory allocation: new & delete • References (automatically dereferenced pointers) • Function templates: data types as parameters • Tag names as new data types • Better type system: tighter use of void *
  • 6. 6 Convenient Syntax for Inline Comments • Anything from // to the end of line is considered a comment and thus ignored by the compiler. • The C-syntax for comments, /* … */, can still be used for multi-tine comments. int i; // i is an integer that will index the next array double x[10]; // an array that will store user input // and will then be sorted.
  • 7. 7 Declaration Anywhere • Declarations need no longer be at the head of blocks. • Variables and functions can be declared any time, anywhere in a program, preferably as close to where a variable is used the first time. • For example: note i is declared within for for (int i=0;i<n;i++)
  • 8. 8 Function Overloading • Two or more functions can have the same name but different parameters • Example: int max(int a, int b) { if (a>= b) return a; else return b; } float max(float a, float b) { if (a>= b) return a; else return b; }
  • 9. 9 Default Arguments • A default argument is a value given in the function declaration that the compiler automatically inserts if the caller does not provide a value for that argument in the function call. • Syntax: return_type f(…, type x = default_value,…);
  • 10. 10 Default Arguments (Examples) • The default value of the 2nd argument is 2. • This means that if the programmer calls pow(x), the compiler will replace that call with pow(x,2), returning x2 double pow(double x, int n=2) // computes and returns xn
  • 11. 11 Default Arguments (Rules) • Once an argument has a default value, all the arguments after it must have default values. • Once an argument is defaulted in a function call, all the remaining arguments must be defaulted. int f(int x, int y=0, int n) // illegal int f(int x, int y=0, int n=1) // legal
  • 12. 12 Examples of Legal/Illegal Defaulting in Function Calls • Let substring be a function whose prototype is: • Assume • Which call to substring is OK and which is not OK? If OK, what is it equivalent to? – substring(p) – substring(p,10) – substring( ) char * substring (char *p, int length=10, int pos=0) char *p=“hello”;
  • 13. 13 Default Arguments and Function Overloading • Default arguments and function overloading can give rise to an ambiguity • Consider an overloaded function f where one declaration has default arguments that, if removed, makes the function look identical to a second declaration, as in 1. int f(int x, int y=0); returns xy 2. int f(int x); // returns 2x If we call f(2), is it to f in (1) or (2)? The 1st returns 1. The 2nd returns 4.
  • 14. 14 Default Arguments and Function Overloading (Contd.) • If overloaded declarations of a function with default arguments cause ambiguity, the compiler gives an error message. • It is the responsibility of the programmer not to cause such ambiguities.
  • 15. 15 Example of Function Overloading and Default Args // Precondition: x[] is a double array of length n. // n is a positive integer. If missing, it defaults to 10 // Postcondition: the output is the maximum in x[] double max(double x[], int n=10){ double M = x[0]; // M is the maximum so far for (int i=1;i<n;i++) if (x[i]>M) M=x[i]; return M; }
  • 16. 16 Overloading & Defaulting Example (Contd.) // Precondition: x[] is an int array of length n. // n is a positive integer. If missing, it defaults to 10 // Postcondition: the output is the maximum in x[] int max(int x[], int n=10){ int M = x[0]; // M is the maximum so far for (int i=1;i<n;i++) if (x[i]>M) M=x[i]; return M; }
  • 17. 17 Simplified IO • Instead of the complicated syntax of printf and scanf, and the many variations of print and scan, C++ offers a much simpler syntax • For standard output, use cout • For standard input, use cin • File IO is also simpler, and will be discussed later • Note: one can still use the IO syntax of C in C++
  • 18. 18 Cout • For printing output, use this syntax: This prints out the string or the value of the extpression. • For output chaining, use this syntax Each Si is a string or an expression. The effect is to print out the value of S1 followed by the value of S2, followed by the value of S3. cout << a string or an expression; cout << S1 <<S2<<S3<<endl;
  • 19. 19 Cout (Contd.) • The reserved word, endl, ensures that the next cout command prints its stuff on a new line. • New lines can also be added using “n”.
  • 20. 20 Cout (Examples) Statements Output int x=3; double y =4.5; cout <<“the value of x=“<<x; cout<<“; y=“<<y<<endl; cout <<“x+y”<<x+y; the value of x=3; y=4.5 x+y=7.5 int x=3; double y =4.5; cout <<“x = “<<x<<“n”; cout<<“y=“<<y; cout <<“nx+y”<<x+y; x = 3 y=4.5 x+y=7.5
  • 21. 21 Cin • For reading input values into variables: • This reads the input from the standard input (say the screen for now), puts the first read value in variableName1, the second read value in variableName2, and the third read value in variableName3. cin >> variableName1 >> variableName2 >> variableName3;
  • 22. 22 Cin (Examples) • Suppose you want to read an int value and a double value into variables n and x. • This code will do it (see next slide): int n; double x; cout<<“enter an int, a space, and a double: “; cin>>n>>x; // use of cin cout<<“You entered int n=“<<n; cout<<“, and double x=“<<x<<endl;
  • 23. 23 • If you run that code, you first get: • Let’s say, you enter: -3 9.8 • The code next will store –3 in n, and 9.8 in x, and print out to you: Enter an int, a space, and a double: Enter an int, a space, and a double: -3 9.8 You entered int n=-3, and double y=9.8
  • 24. 24 A new Boolean data type: bool • A bool variable is a variable that can have only two values: true or false. • C does not have Boolean values or variables • Instead, any non-zero was considered the equivalent of true , and 0 the equivalent of false.
  • 25. 25 Example of bool // Precondition: x[] is an integer array of length n. // n is a positive integer. // Postcondition: The output is true if the elements // of the input array are all positive,. Else, false. bool isAllPositive(int x[], int n){ for(int i=0;i<n;i++) if (x[i] <= 0) return false; return true; }
  • 26. 26 A Comprehensive Example #include <cstdlib> #include <iostream> using namespace std; // codes for isAllPositive( ), and for overloaded // function max( ) should be inserted here int main(int argc, char *argv[]){ cout << " enter five integers :"; int x[5]; int n=5; for (int i=0;i<n;i++) // read the input to x[] cin>>x[i];
  • 27. 27 cout << "You entered: "; for (int i=0;i<n;i++) cout << x[i]<<" "; if (isAllPositive(x,n)) cout << “nYour data is all positiven"; else cout << “n Your data is not all positiven"; int M = max(x,n); cout<<“Your maximum value is: "<<M<<endl; } // end of main( )
  • 28. 28 Easier Dynamic Memory Allocation: new & delete • new corresponds to malloc/calloc in C • delete corresponds to free in C • The syntax of new has forms: • The semantics of this syntax is explained next –type *pointer = new type; // type is a built-in // or user-defined data type. –type *pointer = new type[n]; // type as above
  • 29. 29 Semantics of new • For type *pointer = new type; : – The system allocates dynamically (during execution) a chunk of memory large enough to hold data of the specified type, and returns a pointer pointing to the address of that chunk. This pointer is stored in the user-provided pointer-variable pointer.
  • 30. 30 Semantics of new [n] • For type *pointer = new type[n]; : – The system allocates dynamically an array of n memory chunks, each large enough to hold data of the specified type, and returns a pointer pointing to the address of that chunk. – The difference between this type of arrays (called dynamic arrays) and conventional arrays is that the size of the latter is constant while the size of the former can vary.
  • 31. 31 Example of new // Precondition: n is a positive integer // Postcondition: computes and prints out the first n // elements of the Fibonacci sequence void fibonacci(int n){ int *x = new int [n]; // creation of a dynamic array x[0]=1; x[1]=1; for (int i=2;i<n;i++) x[i]=x[i-1]+x[i-2]; cout<<"The Fibonacci sequence of "<<n<<" values are:n"; for (int i=0;i<n;i++) cout<<"x["<<i<<"]="<<x[i]<<endl; }
  • 32. 32 Syntax and Semantics of delete • The syntax of delete has two forms: • The first releases the memory of the single memory chunk pointed to by pointer • The second releases the memory allocated to the array pointed to by pointer. – delete pointer ; – delete [] pointer ;
  • 33. 33 References • A reference is an autmatically dereferenced pointer • Syntax of reference declaration: • Semantics: refname becomes another name (or alias) for variable. Any change to the value of variable causes the same change to refname, and vice versa. Type& refname = variable;
  • 34. 34 Illustration of References Statements Outcome int x=17; int& xref = x; cout<<“x=“<<x<<endl; cout<<“xref=“<<xref<<endl; x=17 xref=17 x=x+5; cout<<“x=“<<x<<endl; cout<<“xref=“<<xref<<endl; x=22 xref=22 xref = xref-10; cout<<“x=“<<x<<endl; cout<<“xref=“<<xref<<endl; x=12 xref=12
  • 35. 35 References and Function Call by Reference void swap(int x, int y){ int tmp=x; x=y; y=tmp; } int x=5; int y=10; swap(x,y); cout<<x<<“, “<<y; void swap(int& x, int& y){ int tmp=x; x=y; y=tmp; } int x=5; int y=10; swap(x,y); cout<<x<<“, “<<y; Outcome: 5, 10 // no swap Outcome: 10, 5 // it did swap
  • 36. 36 Templates of Functions (Motivation) • Functions are a great construct because they all the programmer to specify fairly generic parameters (variable arguments), and later call a function multiple times with different argument values, thus saving on programming effort • It will be equally convenient and effort-saving if one can specify generic types that can be substituted with any actual type whenever a function is called
  • 37. 37 Templates of Functions (Purpose and Syntax) • Templates provide that great convenience • They make the data type/types of function arguments and of the return value to be “programmable” • Syntax for declaring template function: template<class type> function_declaration; -Or- template<typename type> function_declaration;
  • 38. 38 Templates of Functions (Example) // Precondition: x[] is an array of length n, of // a generic type. n is a positive integer. // Postcondition: the output is the minimum in x[] template<typename T> T min(T x[], int n){ T m = x[0]; // M is the minimum so far for (int i=1;i<n;i++) if (x[i]<m) m=x[i]; return m; }
  • 39. 39 How to Call a Function Template • The syntax of calling a function template: • Example: functionName<an-actual-type>(parameter-list); int x[]={11, 13, 5, 7, 4, 10}; double y[]={4.5, 7.13, 3, 17}; int minx = min<int>(x,6); double miny=min<double>(y,4); cout<<“the minimum of array x is: “<<minx<<endl; cout<<“the minimum of array y is: “<<miny<<endl;
  • 40. 40 Templates with More than One Generic Type • Templates can have several generic types • Syntax for their declaration: • class can be replaced by typename. template<class type1,class type2> funct_decl;