w8-C++ Programming Basics
w8-C++ Programming Basics
Programming
https://www.tiobe.com/tiobe-index/
https://www.geeksforgeeks.org/top-10-reasons-to-learn-c-plus-plus/?ref=ml_lbp
3
What is C++?
• C++ is a general-purpose, object-oriented programming language
that was designed by Bjarne Stroustrup in 1979 to be an
extension of the C language.
• C vs. C++
https://www.azquotes.com/author/14260-Bjarne_Stroustrup
4
What is C++?
• C++ is a general-purpose, object-oriented programming language
that was designed by Bjarne Stroustrup in 1979 to be an
extension of the C language.
• C vs. C++
https://www.geeksforgeeks.org/history-of-c/
5
What is C++?
▪ Developed by Bjarne Stroustrup, as an extension to the C language
(1979).
▪ Danish Computer Scientist at Bell Telephone Laboratories (Nokia
Bell Labs) in New Jersey
▪ Simula (Used for simulations) : primary language to support
the object-oriented programming- too slow for practice &
practical use.
▪ Worked on “C with Classes” to get advanced object-oriented
programming, into
• the C language
▪ In 1983, the name Change from C with categories to C++.
▪ The ++ operator for incrementing a variable
▪ The language was updated 3 major times in 2011, 2014, and 2017 to
C++11, C++14, and C++17.
6
What is C++?
• C++ vs. C:
- C++ is a superset of C, meaning that any
valid C program is also a valid C++ program
- C++ joins three separate programming
categories:
o Procedural language, represented by C;
o Object-oriented programming (OOP)
language, represented by the class
enhancements in C++;
o Generic programming, supported by
C++ templates.
• In the second half of this course, we
emphasize more on OOP and generic
programing
7
Outline
• Input/output
• Data types:
- Basic data types
- Compound data types
• Reference variables
• Dynamic memory allocation
• Functions
– Inline functions
– Default arguments
– Function overloading
– Function templates
8
Input/Output: Your First C++ Program
Note: c++ program files often end with an
extension of “.cpp” (or “.cc” or “.cxx”)
//main.cpp
#include <iostream> //header of input/output stream
using namespace std; //namespace of standard library
int main()
{
//cout: console output stream object
//endl: start a new line. Its effect is equivalent to ‘\n’ in
C program
cout << “Hello world!” << endl;
cout << “I’m from NTU.\n”;
return 0;
}
9
Input/Output
• Namespaces:
- A new feature introduced in C++
- Designed to avoid possible name conflicts of multiple libraries, e.g.,
two libraries may both define classes (or functions, variables) named List,
Tree, and Node, how can we differentiate them?
- std namespace is defined in the iostream file and contains the
definitions of cin and cout, etc.
#include <iostream> std::cout << “Hello world!”;
//using namespace std; std::cout << std::endl;
int main()
{
std::cout << “Hello world!” << std::endl;
std::cout << “I’m from NTU.\n”;
return 0;
}
If we do not use the namespace directive, we need to keep the
std:: prefix for the functions/variables/objects within the
std namespace.
10
Input/Output
• Namespaces:
// In “greet.h” #include <iostream>
#pragma once #include "greet.h"
#include <iostream> using namespace English;
11
Input/Output #include <iostream>
#include <iomanip> // For setprecision and fixed
using namespace std;
• Output different variable int main() {
float pi = 3.14159;
cout << "Value of Pi: " << pi << endl;
return 0;
}
12
Input/Output – Handle String and
Number
• Using cin:
#include <iostream>
using namespace std;
int main()
{
int age = 0;
char name[20]; Input stream: Y o n g W A N G \n
cout << "What is your name?" <<endl;
Input stream: W A N G \n
cout <<"Your name is "<<name << ", and your age is " << age << "." <<endl;
return 0;
}
The cin will stops at whitespaces like spaces, tabs and newlines.
13
Input/Output – Handle Number
• What will be the result of num for different user inputs?
int num = 0; float num = 0;
cin >> num; cin >> num;
num:234 num:12.92
Input stream: 2 . 9 2 \n
Input stream: 9 8 A N G \n
num:2.92
num:98 Input stream: 9 2 . 2 \n
Input stream: \n 2 . 3 \n
num:92
num:2
Input stream: \n 2 . 2 \n
Input stream: \n w 2 3 G \n
num:2
Failed! Cannot extract a valid part of
Input stream: . 2 4 . 2 \n
digits from the input stream!
num:0.24
1. cin will extract as much as it can to Input stream: y 2 4 2 \n
match the data type, until it reach white Failed! Cannot extract a valid part of
spaces or other non-digit characters. digits from the input stream!
2. After cin extracts the required value, any remaining characters will stay in the input
stream/buffer. 14
Input/Output – Handle Number
• How should we cope with the failure when using cin?
int num = 0; float num = 0;
cin >> num; cin >> num;
1. If cin failed, we need to remove the invalid input from the input stream/buffer by
using cin.ignore();
2. Clear the error state using cin.clear();
3. Ask the user to enter valid input again.
if (cin.fail()) { // Check if input failed
15
Input/Output – Handle String
• cin.getline()and cin.get()
- cin is essentially an object of class istream, so it can have associated
functions
- Both cin.getline()and cin.get()can read the input of one whole
line until reaching a newline character `\n’.
// cin.getline() reads up to (n-1) characters into str and adds a null character at the end; if it
//encounters the delimiter (i.e., `\n’), it will also read `\n’ and then automatically replace it with null.
istream& getline(char* str, streamsize n, char delim = '\n’);
// Reads up to (n-1) characters into str, stopping at delim or max length (n-1) Function
// But it will not read `\n’, and leave it in the input queue Overloading
istream& get(char* str, streamsize n, char delim = '\n');
16
Input/Output – Handle String
• cin.getline()
\0
\n
Sample Output
Enter
Enter
17
Input/Output – Handle String
• cin.get()
#include <iostream>
int main()
{
using namespace std;
const int ArSize = 20;
char name[ArSize];
char dessert[ArSize];
return 0;
}
Sample Output
Enter your name:
Yong Wang Enter
Enter your favorite dessert:
cake Enter
I have some delicious cake for you, Yong Wang.
18
Data Types
• Basic Types: C++ and C share the same basic data types, e.g., char, int,
short, long, float, double, bool, etc.
// limits.cpp -- some integer limits
#include <iostream>
#include <climits> // max/min value symbols are defined in climits file
int main()
{
using namespace std;
short n_short = SHRT_MAX;
int n_int = INT_MAX; // initialize n_int to max int value symbols defined in climits file
long n_long = LONG_MAX;
long long n_llong = LLONG_MAX;
20
Structure
Structure in C program
#include <stdio.h>
#include <string.h>
// Define a structure
struct Person {
char name[50];
int age;
float height;
};
int main() {
struct Person p1 = {"Alice", 25, 175};
printf("Name: %s, Age: %d, Height: %.1f\n", p1.name, p1.age, p1.height);
return 0;
}
21
Structure
Structure in C++ program
#include <iostream>
using namespace std;
struct Person {
char name[50];
int age;
float height;
};
int main() {
Person p1 = {“Alice”, 25, 175};//Difference 2: No need to use `struct` keyword here in C++
p1.display();
return 0;
}
22
Union
• A union is a data format that can hold different data types but only one
type at a time. All these members share the same memory address.
• Unions are memory-efficient, and use only the largest member’s size.
#include <iostream>
using namespace std; Output
union Data { Size of Data: 8 bytes.
short sValue; Size of Short: 2 bytes.
double dValue; Size of Double: 8 bytes.
void printShort() { cout << "sValue: " << sValue << endl; }
void printDouble() { cout << "dValue: " << dValue << endl; } Short: 42
}; sValue: 42
Double: 3.14
int main() { dValue: 3.14
Data data;
cout << "Size of Data: " << sizeof(Data) << " bytes."<<endl;
cout << "Size of Short: " << sizeof(short) <<" bytes." <<endl;
cout << "Size of Double: " << sizeof(double) << " bytes." <<endl<<endl;
24
String
• C++ has two ways to deal with strings:
- C-style string, which is taken from C, i.e., a character array ending with
a null character `\0’.
- string class from the standard library in C++
25
String Class
#include <string>
Function Task
append() Appends a part of string to another string.
at() Obtains the character stored at a specified location.
compare() Compares string against the invoking string.
empty() Returns true if the string is empty; otherwise returns false.
erase() Removes character as specified.
find() Searches for the occurrence of a specified substring.
insert() Inserts character at specified location.
length() Gives number of elements in a string.
replace() Replace specified characters with a given string.
int main() {
string s1("12345");
string s2("abcde");
// Concatenation
string s3 = s1 + s2;
cout<< "s3: "<<s3<<endl;
return 0;
}
Reference Variable
• The reference variable is a new compound type added by C++
• A reference is essentially an alias, or an alternative name, for a previously
defined variable. The reference and original variable name can be used
interchangeably
• You should initialize a reference variable when you declare it. After
that, you cannot change the reference to refer to another variable
int rat;
int & rodent;
rodent = rat; // No, you can’t do this.
Output
rats = 101, rodents = 101
rats address = 0x7fff42eab6c4, rodents address = 0x7fff42eab6c4
bunnies = 50, rats = 50, rodents = 50
bunnies address = 0x7fff42eab6c0, rodents address = 0x7fff42eab6c4
29
Recall: Constant Pointer vs. Pointer to
Constant
• Take int pointer as an example (Y—Changeable, N– Non-changeable)
Description Declaration *ptr ptr
pointer pointing to a const entity const int * ptr N Y
#include <iostream>
int main() {
int value1 = 10;
int value2 = 20;
return 0;
} 30
Recall: Constant Pointer vs. Pointer to
Constant
• Clockwise/Spiral Rule
31
References as Function Parameters
• References are used as function parameters, making the variable name in a
function an alias for a variable in the calling program. Thus, the changes done via
the references within the function will also be reflected outside the function
• Such method of passing arguments is called passing by reference
Successful swapping
32
References as Function Parameters
• References are used as function parameters, making the variable name in a
function an alias for a variable in the calling program. Thus, the changes done via
the references within the function will also be reflected outside the function
• Such method of passing arguments is called passing by reference
Successful swapping
Failed swapping
33
When to Use Reference Arguments?
• There are two main reasons for using reference arguments:
- To allow you to alter a data object in the calling function
- To speed up a program by passing a reference instead of an entire data
object, especially when the data object is large
Const Reference
const int & rodents = rats;
is, in essence, equivalent to
const int * const rodents = &rats
34
When to Use Reference Arguments?
• To avoid unexpected data change, you should declare reference
arguments as const whenever it is appropriate to do so
#include <iostream>
// passing by reference
double calVolume(double& a) {
a = a * a * a;
return a;
}
int main() {
double x = 3.0;
double volume = calVolume(x);
std::cout << "Original side length: " << x << std::endl; // Outputs: 27
std::cout << "Volume of the cube: " << volume << std::endl; // Outputs: 27
return 0;
}
#include <iostream>
// passing by reference
// Use const reference to avoid unexpected variable change
double calVolume(const double& a) {
double volume = a * a * a;
return volume;
}
35
Dynamic Memory
• Dynamic memory refers to the memory that is allocated during runtime
• There are cases when the memory needs of a program can only be
determined during runtime. For example, when the memory needed
depends on user input
• In C++, we use the new operator for allocating dynamic memory, and the
delete operator for freeing previously-allocated dynamic memory
int main() {
int* pt = new int; // Allocate memory for an integer
*pt = 42;
cout << "Value: " << *pt << ", memory address: "<< pt << endl; pt 42
delete pt; // Free memory
cout << "Value: " << *pt << ", memory address: "<< pt << endl; pt ?
pt = nullptr; // prevents dangling pointer, nullptr: null pointer
cout<< "memory address: " << pt <<endl; pt nullptr
return 0;
}
Output
Value: 42, memory address: 0x1a9ea2b0
37
Dynamic Memory
#include <iostream>
using namespace std;
int main() {
int size;
cout << "Enter the number of elements: "; Size = 3
cin >> size;
// Display values
cout << "You entered: ";
for (int i = 0; i < size; i++) {
cout << arr[i] << " ";
}
cout << endl;
? ? ?
// Deallocate memory
delete[] arr;
arr = nullptr; // Prevent dangling pointer pt nullptr
Output
return 0;
} Enter the number of elements: 3
Enter 3 elements: 10 20 30
You entered: 10 20 30
38
Dynamic Memory
• Do remember to use new and delete in parallel to avoid memory
leakage
-- Free the dynamic memory when your program does not need it
39
Outline
• Input/output
• Data types:
- Basic data types
- Compound data types
• Reference variables
• Dynamic memory allocation
• Functions
– Inline functions
– Default arguments
– Function overloading
– Function templates
40
Inline Function
• Inline functions are a C++ enhancement designed to speed up programs.
• There are overheads in calling regular functions, as the program need to
- store memory address of subsequent instructions
- copy function arguments to the stack
- jump to memory location of the function
-…
• For inline functions, the compiler replaces function call with the
corresponding function code and there is no need to jump back and forth
41
Inline Function
42
Inline Function
#include <iostream>
using namespace std;
int main() {
double a, b;
double c = 13.0;
a = square(5.0);
b = square(4.5 + 7.5);
cout << "a = " << a << ", b = " << b << endl;
cout << "c = " << c;
cout << ", c squared = " << square(c++) << endl;
cout << "Now c = " << c << endl;
return 0;
}
Output
a = 25, b = 144
c = 13, c squared = 169
Now c = 14
43
Default Arguments
• A default argument is a value that’s used automatically, if you omit the
corresponding actual argument from a function call.
#include<iostream>
using namespace std;
int main() {
cout<< add(10,20)<<endl; //10+20, 30
cout<<add(10) <<endl; //10+6, 16
cout<<add() <<endl; //5+6, 11
return 0;
}
44
Default Arguments
• When you declare/define a function with an argument list, you must add
defaults from right to left. That is, you cannot provide a default value for
a particular argument unless you also provide defaults for all the
arguments to its right:
int add(int x, int y = 5, int z = 6);//valid
int add(int x = 1, int y = 5, int z);//invalid
int add(int x = 1, int y, int z = 6);//invalid
• When using the a function with default arguments, the actual arguments
are assigned to the corresponding formal arguments from left to right; you
can’t skip over arguments.
int add(int x, int y = 5, int z = 6);
46
Function Overloading
• C++ allows multiple functions to share the same name, which is often
called function overloading or function polymorphism
• We can use function overloading to design multiple functions that do the
same thing, but with different argument lists (a.k.a, function signature).
Different argument lists refer to different argument types or argument
numbers.
int add(int x, int y);
float add(float x, float y); Different argument types
47
Function Overloading
• Below are some examples of invalid function overloading
int add(int x, int y);
Argument names do not matter
int add(int a, int b);
48
Function Templates
• A function template is a generic function description. It defines a function in
terms of a generic type for which a specific type, such as int or double,
can be substituted.
• With function templates, we can easily implement the same function for
multiple data types.
49
Function Templates
#include <iostream>
int main() {
int i = 5, j = 10;
std::cout << "Max(i, j): " << getMax(i, j) << std::endl;
return 0;
}
Output
30
16
11
50
References:
51
Questions?
Thank You!