SlideShare a Scribd company logo
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

PPTX
Operators and expressions in C++
PPT
Operators in C++
PPTX
Templates in c++
PPT
Basics of c++ Programming Language
PDF
PPT
C program
PPTX
Loops in C Programming Language
PPTX
07. Virtual Functions
Operators and expressions in C++
Operators in C++
Templates in c++
Basics of c++ Programming Language
C program
Loops in C Programming Language
07. Virtual Functions

What's hot (20)

PPTX
Inline Functions and Default arguments
PPTX
The string class
PPTX
Introduction to Java -unit-1
PDF
Introduction to c++ ppt 1
PPTX
Loop optimization
PPT
One Dimensional Array
PPTX
Python-Classes.pptx
PPTX
virtual function
PDF
Constructor and Destructor
PPTX
Data types in c++
PPTX
Presentation on C++ Programming Language
PPTX
Inheritance in java
PPS
Wrapper class
PPTX
PPTX
Principal of objected oriented programming
PPTX
classes and objects in C++
PDF
Introduction to c++ ppt
PPTX
Constructors in C++
PDF
Exception handling
Inline Functions and Default arguments
The string class
Introduction to Java -unit-1
Introduction to c++ ppt 1
Loop optimization
One Dimensional Array
Python-Classes.pptx
virtual function
Constructor and Destructor
Data types in c++
Presentation on C++ Programming Language
Inheritance in java
Wrapper class
Principal of objected oriented programming
classes and objects in C++
Introduction to c++ ppt
Constructors in C++
Exception handling
Ad

Viewers also liked (20)

PDF
Data types
PDF
C++ OOPS Concept
PPTX
functions of C++
PPTX
Function in c
PPT
C++ programming
PPTX
Function in C program
PPT
Basics of C programming
PDF
Chapter 2 basic element of programming
ODP
C++ Function
PPT
User defined data type
PDF
C++ Programming
PPT
IP Addressing and subnetting
PPT
Data type
PPTX
Lecture 03 Software Risk Management
PPTX
Characteristics of Software
PPTX
Array and string
PPT
Parm
PPT
Bitwise operators
PPTX
C Language (All Concept)
Data types
C++ OOPS Concept
functions of C++
Function in c
C++ programming
Function in C program
Basics of C programming
Chapter 2 basic element of programming
C++ Function
User defined data type
C++ Programming
IP Addressing and subnetting
Data type
Lecture 03 Software Risk Management
Characteristics of Software
Array and string
Parm
Bitwise operators
C Language (All Concept)
Ad

Similar to C++ Language (20)

PPT
2.overview of c++ ________lecture2
PPTX
C++ lectures all chapters in one slide.pptx
PPTX
C_plus_plus
PPTX
cppt-170218053903.pptxhjkjhjjjjjjjjjjjjjjj
PPTX
C++ Overview PPT
PDF
c-for-c-programmers.pdf
PDF
C++primer
PPT
Chapter02-S11.ppt
PPT
PPTX
c++ introduction, array, pointers included.pptx
PPT
programming week 2.ppt
PPT
Chapter 2 Introduction to C++
PDF
C++ L01-Variables
PPTX
Introduction to c++
PPT
C++ Introduction
PPT
CPP Language Basics - Reference
PPSX
Esoft Metro Campus - Programming with C++
PPTX
Nitin Mishra 0301EC201039 Internship PPT.pptx
2.overview of c++ ________lecture2
C++ lectures all chapters in one slide.pptx
C_plus_plus
cppt-170218053903.pptxhjkjhjjjjjjjjjjjjjjj
C++ Overview PPT
c-for-c-programmers.pdf
C++primer
Chapter02-S11.ppt
c++ introduction, array, pointers included.pptx
programming week 2.ppt
Chapter 2 Introduction to C++
C++ L01-Variables
Introduction to c++
C++ Introduction
CPP Language Basics - Reference
Esoft Metro Campus - Programming with C++
Nitin Mishra 0301EC201039 Internship PPT.pptx

More from Syed Zaid Irshad (20)

PDF
Data Structures & Algorithms - Spring 2025.pdf
PDF
Operating System.pdf
PDF
DBMS_Lab_Manual_&_Solution
PPTX
Data Structure and Algorithms.pptx
PPTX
Design and Analysis of Algorithms.pptx
PPTX
Professional Issues in Computing
PDF
Reduce course notes class xi
PDF
Reduce course notes class xii
PDF
Introduction to Database
PDF
C Language
PDF
Flowchart
PDF
Algorithm Pseudo
PDF
Computer Programming
PDF
ICS 2nd Year Book Introduction
PDF
Security, Copyright and the Law
PDF
Computer Architecture
PDF
Data Communication
PDF
Information Networks
PDF
Basic Concept of Information Technology
PDF
Introduction to ICS 1st Year Book
Data Structures & Algorithms - Spring 2025.pdf
Operating System.pdf
DBMS_Lab_Manual_&_Solution
Data Structure and Algorithms.pptx
Design and Analysis of Algorithms.pptx
Professional Issues in Computing
Reduce course notes class xi
Reduce course notes class xii
Introduction to Database
C Language
Flowchart
Algorithm Pseudo
Computer Programming
ICS 2nd Year Book Introduction
Security, Copyright and the Law
Computer Architecture
Data Communication
Information Networks
Basic Concept of Information Technology
Introduction to ICS 1st Year Book

Recently uploaded (20)

PPTX
CH1 Production IntroductoryConcepts.pptx
PDF
Mitigating Risks through Effective Management for Enhancing Organizational Pe...
PPTX
MET 305 2019 SCHEME MODULE 2 COMPLETE.pptx
PDF
July 2025 - Top 10 Read Articles in International Journal of Software Enginee...
PPTX
Geodesy 1.pptx...............................................
PDF
Model Code of Practice - Construction Work - 21102022 .pdf
PPTX
Recipes for Real Time Voice AI WebRTC, SLMs and Open Source Software.pptx
PDF
BMEC211 - INTRODUCTION TO MECHATRONICS-1.pdf
PDF
Mohammad Mahdi Farshadian CV - Prospective PhD Student 2026
PPTX
MCN 401 KTU-2019-PPE KITS-MODULE 2.pptx
PDF
The CXO Playbook 2025 – Future-Ready Strategies for C-Suite Leaders Cerebrai...
PDF
Arduino robotics embedded978-1-4302-3184-4.pdf
PDF
Structs to JSON How Go Powers REST APIs.pdf
PPT
Project quality management in manufacturing
PPTX
CYBER-CRIMES AND SECURITY A guide to understanding
PDF
Embodied AI: Ushering in the Next Era of Intelligent Systems
PDF
composite construction of structures.pdf
DOCX
ASol_English-Language-Literature-Set-1-27-02-2023-converted.docx
PDF
PRIZ Academy - 9 Windows Thinking Where to Invest Today to Win Tomorrow.pdf
PPTX
UNIT-1 - COAL BASED THERMAL POWER PLANTS
CH1 Production IntroductoryConcepts.pptx
Mitigating Risks through Effective Management for Enhancing Organizational Pe...
MET 305 2019 SCHEME MODULE 2 COMPLETE.pptx
July 2025 - Top 10 Read Articles in International Journal of Software Enginee...
Geodesy 1.pptx...............................................
Model Code of Practice - Construction Work - 21102022 .pdf
Recipes for Real Time Voice AI WebRTC, SLMs and Open Source Software.pptx
BMEC211 - INTRODUCTION TO MECHATRONICS-1.pdf
Mohammad Mahdi Farshadian CV - Prospective PhD Student 2026
MCN 401 KTU-2019-PPE KITS-MODULE 2.pptx
The CXO Playbook 2025 – Future-Ready Strategies for C-Suite Leaders Cerebrai...
Arduino robotics embedded978-1-4302-3184-4.pdf
Structs to JSON How Go Powers REST APIs.pdf
Project quality management in manufacturing
CYBER-CRIMES AND SECURITY A guide to understanding
Embodied AI: Ushering in the Next Era of Intelligent Systems
composite construction of structures.pdf
ASol_English-Language-Literature-Set-1-27-02-2023-converted.docx
PRIZ Academy - 9 Windows Thinking Where to Invest Today to Win Tomorrow.pdf
UNIT-1 - COAL BASED THERMAL POWER PLANTS

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;