C++ Cheat Sheet: Syntax

Download as pdf or txt
Download as pdf or txt
You are on page 1of 92

C++ Cheat Sheet

Syntax

Let’s kick off our C++ reference sheet with syntax.

#include <iostream>
using namespace std;

int main() {
cout << "Hello World!";
return 0;
}

● Line 1: ‘#include <iostream>’ specifies the header file library, which helps you deal with
input and output objects like “cout.” Header files are used to add specific functionality to
C++ programs.
● Line 2: ‘using namespace std’ allows you to use names for objects and variables from
the standard library.
● Line 3: Blank line. C++ ignores the spaces present within the code.
● Line 4: ‘int main()’, which is a function. Any code within the curly brackets {} will be
executed.
● Line 5: cout is an object used along with the insertion operator (<<) to print the output
text.
● Line 6: return 0 is used to end the main function.

While writing code in C++, always make sure you end each line with a semicolon to specify the
end of the line. You must also add the closing bracket to end the main function; otherwise, you’ll
get errors while compiling the code.

Comments
In C++, the compiler ignores the text followed by the comments. C++ supports two different
types of comments:

//: specifies the single-line comment.


/* ….*/: specifies the multi-line comment.
Data Types
Data types specify the type of the data variable. The compiler allocates the memory based on
the data types. The following are the C++ data types:

● Built-in or primitive data types: Pre-defined data types that can be used directly,
including Integer, Character, Boolean, Floating Point, Double Floating Point, Valueless or
Void, and Wide Character.
● Derived data types: Derived from primitive data types: function, array, pointer, and
reference.
● User-defined data types: Defined by users: class, structure, union, enumeration, and
Typedef.

Variables
Variables store the data values. C++ supports various types of variables, such as int, double,
string, char, and float.

For example:
int num = 12; // Integer
string name = "Unity Buddy"; // String(text)
char ch = 'U'; //character
float fl = 5.99; // Floating point number

You can use alphabets, numbers, and the underscore for a variable name. However, variables
cannot start with numbers or the underscore ‘_’ character. Instead, they begin with letters
followed by numbers or the underscore ‘_’ character. Moreover, you cannot use a keyword for
the variable name.

Variables Scope
In C++, you can declare your variables within three parts of the program, also known as the
scope of the variables:

Local Variables
These variables are declared within a function or block of code. Their scope is only limited to
that function or block and cannot be accessed by any other statement outside that block.

For example:

#include <iostream>
using namespace std;

int main () {
// Local variable:
int a, b;
int c;

// initialization
a = 10;
b = 20;
c = a + b;

cout << c;

return 0;
}

Global Variables
Global variables are accessible to any function, method, or block of the program. Usually, it is
defined outside all the functions. The value of the global variable is the same throughout the
program.

For example:

#include <iostream>
using namespace std;

// Global variable:
int g;

int main () {
// Local variable:
int a, b;

// initialization
a = 10;
b = 20;
g = a + b;

cout << g;

return 0;
}

Data Type Modifiers


Data type modifiers are used to modify a data type’s maximum length of data. The following
table will help you understand the size and range of built-in data types when combined with
modifiers. There are four different types of modifiers available in C++, namely signed, unsigned,
short, and long.

Data Type Size (in bytes) Range


short int 2 -32,768 to 32,767
unsigned short int 2 0 to 65,535
unsigned int 4 0 to 4,294,967,295
-2,147,483,648 to
int 4 2,147,483,647
-2,147,483,648 to
long int 4 2,147,483,647
unsigned long int 4 0 to 4,294,967,295
long long int 8 -(2^63) to (2^63)-1
0 to
unsigned long long 18,446,744,073,709,551,6
int 8 15
signed char 1 -128 to 127
unsigned char 1 0 to 255
float 4
double 8
long double 12
wchar_t 2 or 4 1 wide character

Literals
Literals in C++ are data that you can use to represent the fixed values. You can use them
directly within the code.

For example, 1, 2.5, “s”, etc.

There are different types of literal available in C++, as explained below:

Integer literal
An integer literal is numeric and does not have any fractional or exponential part.

For example:

Decimal (base 10): 0, -9, 22, etc.


Octal (base 8) : 021, 077, 033, etc.
Hexadecimal (base 16): 0x7f, 0x2a, 0x521, etc.

Floating-Point Literals
These are numeric literals that have either a fractional part or an exponent part.

For example: (-2.0, 0.8589, -0.26E -5).

Character Literal
These are single characters enclosed within a single quote.

For example: ‘a’, ‘F’, ‘2’, etc.


Escape Sequences
You can use escape sequences in C++ for untypable characters that have special meaning in
C++.

For example:

Escape
Sequences Characters
\b Backspace
\f Form feed
\n Newline
\r Return
\t Horizontal tab
\v Vertical tab
\\ Backslash
Single quotation
\' mark
Double quotation
\" mark
\? Question mark
\0 Null Character

String Literal
This is a sequence of characters enclosed within double quotes.

For example:

"good" string constant


"" null string constant
"" string constant of six white space
"x" string constant having a single character
"Earth is round\n" prints string with a newline
Constants
To create a variable for which you do not want to change the values, you can use the “const”
keyword.

For example:

const int LIGHT_SPEED = 2997928;


LIGHT_SPEED = 2500 // cannot change the value

Math Functions
C++ provides several functions that allow you to perform mathematical tasks. The following
table highlights all the basic math functions available in C++:

Function Description
abs(x) Returns the absolute value of x
acos(x) Returns the arccosine of x
asin(x) Returns the arcsine of x

atan(x) Returns the arctangent of x


cbrt(x) Returns the cube root of x
ceil(x) Returns the value of x rounded up to its nearest integer
cos(x) Returns the cosine of x
cosh(x) Returns the hyperbolic cosine of x
exp(x) Returns the value of Ex

expm1(x) Returns ex -1
fabs(x) Returns the absolute value of a floating x
fdim(x, y) Returns the positive difference between x and y
floor(x) Returns the value of x rounded down to its nearest integer
hypot(x, y) Returns sqrt(x2 +y2) without intermediate overflow or underflow
fma(x, y, z) Returns x*y+z without losing precision
fmax(x, y) Returns the highest value of a floating x and y
fmin(x, y) Returns the lowest value of a floating x and y
fmod(x, y) Returns the floating point remainder of x/y
pow(x, y) Returns the value of x to the power of y
sin(x) Returns the sine of x (x is in radians)
sinh(x) Returns the hyperbolic sine of a double value
tan(x) Returns the tangent of an angle
tanh(x) Returns the hyperbolic tangent of a double value

User Inputs
C++ supports “cout” and “cin” for displaying outputs and for taking inputs from users,
respectively. The cout uses the iteration operator (<<), and cin uses (>>).

For example:

int x; // declaring a variable


cout << "Type a number: "; // Type any number and hit enter
cin >> x; // Get user input from the keyboard
cout << "Your number is: " << x; // Display the value

Strings
A string is a collection or sequence of characters enclosed within double-quotes.

For example:

string str= "Hello";

To use string within your code, you must include the string library using this code line:

#include <string>

C++ will then allow you to perform various functions to manipulate strings. The following table
describes the function names and their descriptions:

Function Description
int compare(const string& str) Compare two string objects

int length() Finds the length of the string


void swap(string& str) Swaps the values of two string objects
string substr(int pos, int n) Creates a new string object of n characters

int size() Return the length of the string in terms of bytes


void resize(int n) Resizes the length of the string up to n characters
string& replace(int pos, int len, Replaces the portion of the string beginning at character
string& str) position pos and spans len characters

string& append(const string& Adds a new character at the end of another string object
str)

char& at(int pos) Accesses an individual character at specified position pos


int find(string& str, int pos, int Finds a string specified in the parameter
n)
int find_first_of(string& str, int Find the first occurrence of the specified sequence
pos, int n)

int find_first_not_of(string& str, Searches for the string for the first character that does not
int pos, int n ) match with any of the characters specified in the string

int find_last_of(string& str, int Searches for the string for the last character of a specified
pos, int n) sequence

int find_last_not_of(string& str, Searches for the last character that does not match with the
int pos) specified sequence

string& insert() Inserts a new character before the character indicated by the
position pos
int max_size() Finds the maximum length of the string
void push_back(char ch) Adds a new character ch at the end of the string

void pop_back() Removes the last character of the string


string& assign() Assigns new value to the string
int copy(string& str) Copies the contents of string into another

void clear() Removes all the elements from the string


const_reverse_iterator Points to the last character of the string
crbegin()
const_char* data() Copies the characters of string into an array
bool empty() Checks whether the string is empty or not
string& erase() Removes the characters as specified
char& front() Returns a reference of the first character
string& operator+=() Appends a new character at the end of the string

string& operator=() Assigns a new value to the string


char operator[](pos) Retrieves a character at specified position pos
int rfind() Searches for the last occurrence of the string
iterator end() Refers to the last character of the string
reverse_iterator rend() Points to the first character of the string

void shrink_to_fit() Reduces the capacity and makes it equal to the size of the
string
char* c_str() Returns pointer to an array containing a null terminated
sequence of characters
void reserve(inr len) Requests a change in capacity
allocator_type get_allocator(); Returns the allocated object associated with the string

Operators
C++ supports different types of operators to add logic to your code and perform operations on
variables and their respective values. Here are the C++ operator types:

Arithmetic Operators
You can perform common mathematical operations with arithmetic operators.

Operator Name Example


+ Addition x+y

- Subtraction x-y

* Multiplication x*y
/ Division x/y

% Modulus x%y
++ Increment ++x

-- Decrement --x

Assignment Operators
You can assign values to variables with assignment operators.

Operator Example Description Same As


= x=5 For assigning a value to x = 5
the variable.
+= x += 3 It will add the value 3 to x = x + 3
the value of x.
-= x -= 3 It will subtract the value 3 x = x - 3
from the value of x.
*= x *= 3 It will multiply the value 3 x = x * 3
with the value of x.
/= x /= 3 It will divide the value of x x = x / 3
by 3.
%= x %= 3 It will return the reminder x = x % 3
of dividing the the value x
by 3.
&= x &= 3 x=x&3
|= x |= 3 x=x|3
^= x ^= 3 x=x^3
>>= x >>= 3 x = x >> 3
<<= x <<= 3 x = x << 3

Comparison Operators
You can use these operators to compare two values to return a true or false value. It will return
true if both the values match, and false if they don’t match.

Operator Name Example


== Equal to x == y
!= Not equal x != y
> Greater than x>y
< Less than x<y
>= Greater than or x >= y
equal to
<= Less than or x <= y
equal to

Logical Operators
These operators determine the logic between variables.

Operator Name Description Example


&& Logical and Returns true if both statements are true x < 5 && x < 10

|| Logical or Returns true if one of the statements is x < 5 || x < 4


true
! Logical not Reverse the result, returns false if the !(x < 5 && x < 10)
result is true

Decision-Making Statements
Decision-making statements in C++ decide the flow of program execution. Here, programmers
specify more than one condition. If a condition holds true the statements in that block are
executed. Otherwise, the statements from other blocks are executed instead.

C++ has various decision-making instructions:

● If statement
● if..else statement
● Switch statement
● Nested if statement
● Nested switch statement
● Ternary operator

If Statement
This is the most basic type of decision-making statement. It instructs the compiler to execute the
block of code only if the condition holds true.

Syntax:
if (expression)
{ //code}

Example:

#include <iostream>
using namespace std;

int main () {
int b = 10;
if( b < 20 ) {
cout << "b is less than 20;" << endl;
}
cout << "value of a is : " << b << endl;

return 0;
}

If..Else Statement
This is an extension of the ‘if’ statement. It instructs the compiler to execute the ‘if’ block only if
the specified condition is true. Otherwise, it executes the ‘else’ block.

Syntax:

if (expression)
{//code}
else
{//code}

Example:

#include <iostream>
using namespace std;

int main () {
int b = 10;
if( b < 20 ) {
cout << "b is less than 20;" << endl;
}
cout << "value of a is : " << b << endl;

return 0;
}

Switch Statement
When you need to execute conditions against various values, you can use switch statements.

Syntax:

switch(expression) {
case constant-expression :
statement(s);
break; //optional
case constant-expression :
statement(s);
break; //optional

default : //Optional
statement(s);
}

Example:

#include <iostream>
using namespace std;

int main () {
// local variable declaration:
char grade = 'D';

switch(grade) {
case 'A' :
cout << "Outstanding!" << endl;
break;
case 'B' :
case 'C' :
cout << "Well done" << endl;
break;
case 'D' :
cout << "Pass" << endl;
break;
case 'F' :
cout << "Try again" << endl;
break;
default :
cout << "Invalid grade" << endl;
}
cout << "Your grade is " << grade << endl;

return 0;
}

Nested If Statement
This is an “if” statement inside another “if” statement. You can use this type of statement when
you need to base a specific condition on the result of another condition.

Syntax:

if( boolean_expression 1) {
// Executes when the boolean expression 1 is true
if(boolean_expression 2) {
// Executes when the boolean expression 2 is true
}
}

Example:

#include <iostream>
using namespace std;

int main () {
// local variable declaration:
int x = 100;
int y = 200;

if( x == 100 ) {
if( y == 200 ) {
cout << "Value of x is 100 and y is 200" << endl;
}
}
cout << "Exact value of x is : " << x << endl;
cout << "Exact value of y is : " << y << endl;

return 0;
}

Nested Switch Statement


You can include one switch statement within another switch statement.

Syntax:

switch(ch1) {
case 'A':
cout << "This A is part of outer switch";
switch(ch2) {
case 'A':
cout << "This A is part of inner switch";
break;
case 'B': // ...
}
break;
case 'B': // ...
}

Example:

#include <iostream>
using namespace std;

int main () {
int x = 100;
int y = 200;

switch(x) {
case 100:
cout << "This is part of outer switch" << endl;
switch(y) {
case 200:
cout << "This is part of inner switch" << endl;
}
}
cout << "Exact value of x is : " << x << endl;
cout << "Exact value of y is : " << y << endl;

return 0;
}

Ternary Operator

Exp1 ? Exp2 : Exp3;

First, expression Exp1 is evaluated. If it’s true, then Exp2 is evaluated and becomes the value of
the entire ‘?’ expression. If Exp1 is false, then Exp3 is evaluated and its value becomes the
value of the expression.

Loops
Loops are used to execute a particular set of commands for a specific number of time based on
the result of the evaluated condition. C++ includes the following loops

● While loop
● Do-while loop
● For loop
● Break statement
● Continue statement

While Loop
The loop will continue till the specified condition is true.

while (condition)
{code}
Do-While Loop
When the condition becomes false, the do-while loop stops executing. However, the only
difference between the while and do-while loop is that the do-while loop tests the condition after
executing the loop. Therefore, the loop gets executed at least once.

do
{
Code
}
while (condition)

For Loop
You can use the for loop to execute a block of code multiple times. This loop runs the block until
the condition specified in it holds false.

for (int a=0; i< count; i++)


{
Code
}

Break Statement
This is used to break the flow of the code so the remaining code isn’t executed. This brings you
out of the loop.

For example:

for (int i = 0; i < 10; i++) {


if (i == 4) {
break;
}
cout << i << "\n";
}

Continue Statement
This statement will break the flow and take you to the evaluation of the condition. Later, it starts
the code execution again.
For example:

for (int i = 0; i < 10; i++) {


if (i == 4) {
continue;
}
cout << i << "\n";
}

Arrays
Arrays are derived data types that store multiple data items of similar types at contiguous
memory locations.

For example:

string vehicles [4]; //declaring array to store up to 4 variables.


string vehicles[4]= {"car", "scooter", "cycle", "bike"}; //initializing
the array

Accessing Array Values


You need to use the index number to access the elements stored in an array.

string vehicles[4]= {"car", "scooter", "cycle", "bike"};


cout << vehicles [0];

Changing Array Elements


You can change the elements stored in an array using the index number.

string vehicles[4]= {"car", "scooter", "cycle", "bike"};


vehicles [0]= " "airplane";
cout << vehicles[0];
Functions
A function is a group of instructions to carry out a specific task. The common function in every
C++ program is the main() function. You can even break down your complex code into multiple
small functions and execute them separately.

For this, you need to declare, define, and call that function. C++ has several built-in functions
that you can call directly within any program.

Defining a Function
The following is the syntax for defining a function in C++:

return_type function_name( parameter list ) {


body of the function
}

Where:

● return_type specifies the type of value being returned by that function.


● function_name specifies the name of the function and needs to be unique.
● parameter list allows you to pass more than one value to your function, along with their
data types.
● body of the function specifies the set of instructions to accomplish a task.

For example:

int max(int num1, int num2) { // declaring the function max


int result;

if (num1 > num2)


result = num1;
else
result = num2;

return result;
}
Calling a Function
You must call a function wherever you need it in your program.

For example:

#include <iostream>
using namespace std;

// function declaration
int max(int num1, int num2);

int main () {
int a = 100;
int b = 200;
int ret;

ret = max(a, b);


cout << "Max value is : " << ret << endl;

return 0;
}

Function Arguments
You can pass arguments in three ways:

● Call by value: Passes the actual value of an argument into the formal parameter
of the function. It will not make any change to the parameter inside the function
and does not effect on the argument.
● Call by pointer: You can copy an argument address into the formal parameter.
Here, the address accesses the actual argument used in the call. This means
that changes made to the parameter affect the argument.
● Call by reference: You can copy an argument reference into the formal
parameter. The reference accesses the actual argument used in the call. This
means that changes made to the parameter affect the argument.

Storage Classes
Storage classes define the visibility of the variables and functions. C++ supports various storage
classes, like auto, register, extern, static, and mutable.
Auto Storage Class
By default, C++ uses this storage class for all variables.

For example:

{
int var;
auto int var1;
}

You can only use the “auto” within functions for defining the local variables.

Register Storage Class


This storage class defines the local variables to be stored within the register rather than in RAM.
It’s useful when you want to access the variable frequently, such as counters. The size of the
variable will have a maximum size equal to the register size.

For example:

{
register int miles;
}

Static Storage Class


The static storage class tells the compiler to maintain local variables throughout the program
without needing to create and destroy them when it comes into and goes out of scope. Defining
a variable as static means it will maintain its values between function calls.

Global variables are static, which means their scope will be restricted to their declared file. If you
specify a class data member as static, it creates only one copy of that member that all objects of
its class will share.

For example:

#include <iostream>

// Function declaration
void func1(void);
static int count = 10; /* Global variable */

main() {
while(count--) {
func();
}

return 0;
}

// Function definition
void func1( void ) {
static int i = 5; // local static variable
i++;
std::cout << "i is " << i ;
std::cout << " and count is " << count << std::endl;
}

Extern Storage Class


The extern storage class provides a reference of a global variable and makes it visible to ALL
the program files. When you specify a variable as ‘extern', the variable cannot be initialized
because it points the variable name at a storage location that has been previously defined.

In case of multiple files where you define a global variable or function, also to be used in other
files, extern will provide a reference in another file of defined variable or function. You must use
the extern modifier when you have to share the same global variables or functions between two
or more files.

For example:

Program 1
#include <iostream>
int count ;
extern void write_extern();

main() {
count = 5;
write_extern();
}
STL Cheat Sheet

Creation
• Make an empty vector of integers.

vector< int > iseq1;

• Make a 10-element vector of doubles, each initialized to -1.

vector< double > iseq2( 10, -1 );

• A value that is a 10-element vector of ints, each initialized to 50.

vector< double >( 10, 50 );

• Make a string, integer pair initialized to “up”, 15.

pair< string, int > myPair( "up", 15 );

• A value that is a double, integer pair containing 3.14, 7.

pair< double, int >( 3.14, 7 ); // Types given explicitly


make_pair( 3.14, 7 ); // Types inferred by the compiler.

• Make a 100-element vector of string, double pairs, each initialized to “height”, -1.

vector< pair< string, double > > pseq( 100, make_pair( string("height"), -1.0 ) );

• Make an empty vector of vectors of ints.

vector< vector< int > > matrix1;

• Make a 10 × 20 vector of vectors of ints, each element initialized to 3.

vector< vector< int > > matrix2( 10, vector< int >( 20, 3 ) );

• Make an iterator that can point to an element of a vector of ints.

vector< int >::iterator pos;

Access and Modification


• Number of items in a vector (typically unsigned int)

iseq1.size()

• Number of rows in a vector of vectors.

matrix2.size()

1
• Number of elements in the first row of a vector of vectors.

matrix2[ 0 ].size()

• Access first item in a vector (modifiable).

iseq2.front()

• Access last item in a vector (modifiable).

iseq2.back()

• Return an iterator pointing to the first element of the vector.

iseq1.begin()

• Return an iterator pointing to the imaginary position one past the end of the vector.

iseq1.end()

• Return the value of the element at index 5 in the vector (modifiable)

iseq2[ 5 ]

• Value of row 7 in a vector of vectors (modifiable)

matrix2[ 7 ]

• Value at row 7, column 3 in a vector of vectors (modifiable)

matrix2[ 7 ][ 3 ]

• Compute the value of an iterator pointing to the element at index 5 of the vector.

iseq1.begin() + 5

• Access first field of a pair (modifiable)

myPair.first

• Access second field of a pair (modifiable)

myPair.second

2
Insertion and Removal
• Add a integer to the end of a vector.

iseq1.push_back( 20 );

• Add a pair to the end of a vector.

pseq.push_back( make_pair( string("weight"), 175.5 ) );

• Remove last element in a vector.

iseq1.pop_back();

• Insert a value at the start of a vector (linear time).

pseq.insert( pseq.begin(), make_pair( string("weight"), 175.5 ) );

• Insert a value at position 5 in the vector (linear time).

iseq2.insert( pseq.begin() + 5, 99 );

• Append a new row of 100 elements (each set to zero) to the end of this vector of vectors.

matrix1.push_back( vector< int >( 100, 0 ) );

• Insert a new row of 55 elements (each initialized to 75) at the start of this vector of vectors.

matrix1.insert( matrix1.begin(), vector< int >( 55, 75 ) );

• Remove first element from a vector (linear time)

iseq2.erase( pseq.begin() );

• Remove element at index 7 element from a vector (linear time)

pseq.erase( pseq.begin() + 7 );

• Clear contents of the vector.

iseq2.clear();

• Empty the last row of a vector of vectors, but don’t remove it.

matrix2.back().clear();

3
Supporting Algorithms
• Print out every element of a vector.

// Using integer index


for ( unsigned int i = 0; i < iseq1.size(); i++ )
cout << iseq1[ i ] << endl;

// Using iterators
for ( vector< int > :: iterator pos = iseq1.begin(); pos != iseq1.end(); pos++ )
cout << *pos << endl;

• Sort contents of vector based on the < operator.

sort( iseq2.begin(), iseq2.end() );

• Sort contents of vector of pairs, ordering by < for the first fields and using the second fields if first fields
are identical.

sort( pseq.begin(), pseq.end() );

• Sort based on our own sorting function.

// Return true if a should come before b


bool myComparison( pair< string, double > const &a,
pair< string, double > const &b ) {
if ( a.first.length() < b.first.length() )
return true;
if ( b.first.length() < a.first.length() )
return false;

return a.second < b.second;


}

sort( pseq.begin(), pseq.end(), myComparison );

• Return an iterator pointing to the first occurrence of the value 5 in a vector. If not found, return the
given end iterator.

find( iseq1.begin(), iseq1.end(), 5 )

• Reverse sequence of values in the given vector.

reverse( iseq2.begin(), iseq2.end() );

4
STL Cheat Sheet 2 – set, map

Creation
• Make an empty set of integers.
set<int> intSet1;
• Make a set of integers containing the given array of numbers.
int array[] = {10, 20, 30, 40};
set<int> intSet2(array, array + 4);
• Make an empty map from string to int.
map<string, int> siMap1;
• Make an empty map from C-string to int.

struct compareString {
bool operator()(const char *s1, const char *s2) const {
return strcmp(s1, s2) < 0;
}
}

map<const char *, int, compareString> siMap2;

• Declare an iterator for a set of integers.


set<int>::iterator iSetItr;
• Declare an iterator for a string to int map (a map iterator represents a pair of key and value).
map<string, int>::iterator siMapItr;

Access and modification


• Number of items in a set (also for map).
intSet1.size();
• Get an iterator which points to the beginning of the set.
iSetItr = intSet1.begin();
• Get an iterator which points to the end of the map (one past the last element).
siMapItr = siMap1.end();
• Get the value that is pointed to by the set iterator.
*iSetItr
• Get the key that is pointed to by the map iterator.
siMapItr->first
• Get the value that is pointed to by the map iterator.
siMapItr->second

1
Finding
• Find an item in a set (returns an iterator).
intSet1.find(3)
• See if an item is in a set.
if (intSet1.find(3) != intSet1.end()) ...
• Find an item in a map (returns an iterator).
siMap1.find("hello")

• See if an item is in a set.


if (siMap1.find("hello") != siMap1.end()) ...

Insertion and removal


• Place an item in a set.
intSet1.insert(3)
• Place a key/value in a map.
siMap1["hello"] = 3
• Removing an item from a set.
intSet1.erase(intSet1.find(3))
intSet1.erase(intSet1.begin())
• Removing an item from a map.
siMap1.erase(siMap1.find("hello"))
siMap1.erase(siMap1.begin())
• Clearing a set or a map.
intSet1.clear(), siMap1.clear()

2
www.cppforschool.com

Structure
A structure is a collection of variable which can be same or different types. You
can refer to a structure as a single variable and to its parts as members of that
variable by using the dot (.) operator. The power of structures lies in the fact
that once defined, the structure name becomes a user-defined data type and
may be used the same way as other built-in data types, such as int, double,
char.
struct Student
{
int rollno, age;
char name[80];
float marks;
};

int main()
{

// declare two variables of the new type


Student s1, s3;

//accessing of data members


cin >> s1.rollno >> s1.age >> s1.name >> s1.marks;
cout << s1.rollno << s1.age << s1.name << s1.marks;

//initialization of structure variable


Student s2 = {100, 17, "Aniket", 92};
cout << s2.rollno << s2.age << s2.name << s2.marks;

//structure variable in assignment statement


s3 = s2;
cout << s3.rollno << s3.age << s3.name << s3.marks;

return 0;
}
Defining a structure
When dealing with the students in a school, many variables of different types
are needed. It may be necessary to keep track of name, age, Rollno, and
marks point for example.

struct Student
{
int rollno, age;
char name[80];
float marks;
};

Student is called the structure tag, and is your brand new data type, like int,
double or char.

rollno, name, age, and marks are structure members.

Declaring Variables of Type struct


The most efficient method of dealing with structure variables is to define the
structure globally. This tells "the whole world", namely main and any functions
in the program, that a new data type exists. To declare a structure globally,
place it BEFORE void main(). The structure variables can then be defined
locally in main, for example…
struct Student
{
int rollno, age;
char name[80];
float marks;
};

int main()
{
// declare two variables of the new type
Student s1, s3;
………
………
return 0;
}
Alternate method of declaring variables of type struct:
struct Student
{
int rollno, age;
char name[80];
float marks;
} s1, s3;

Accessing of data members


The accessing of data members is done by using the following format:
structure variable.member name
for example

cin >> s1.rollno >> s1.age >> s1.name >> s1.marks;

Initialization of structure variable


Initialization is done at the time of declaration of a variable. For example

Student s2 = {100, 17, "Aniket", 92};

Structure variable in assignment statement

s3 = s2;

The statement assigns the value of each member of s2 to the corresponding


member of s3. Note that one structure variable can be assigned to another only
when they are of the same structure type, otherwise complier will give an error.

Nested structure (Structure within structure)


It is possible to use a structure to define another structure. This is called
nesting of structure. Consider the following program
struct Day
{
int month, date, year;
};

struct Student
{
int rollno, age;
char name[80];
Day date_of_birth;
float marks;
};

Accessing Member variables of Student

To access members of date_of_birth we can write the statements as below :

Student s; // Structure variable of Student

s.date_of_birth.month = 11;
s.date_of_birth.date = 5;
s.date_of_birth.year = 1999;

typedef
It is used to define new data type for an existing data type. It provides and
alternative name for standard data type. It is used for self documenting the
code by allowing descriptive name for the standard data type.

The general format is:


typedef existing datatype new datatype
for example:
typedef float real;
Now, in a program one can use datatype real instead of float.
Therefore, the following statement is valid:
real amount;
Enumerated data type
The enum specifier defines the set of names which are stored internally as
integer constant. The first name was given the integer value 0, the second
value 1 and so on.

for example:

enum months{jan, feb, mar, apr, may} ;

It has the following features:

 It is user defined.
 It works if you know in advance a finite list of values that a data type can
take.
 The list cannot be input by the user or output on the screen.

#define preprocessor directive


The #define preprocessor allows to define symbolic names and constants e.g.
#define pi 3.14159
This statement will translate every occurrence of PI in the program to 3.14159

Macros
Macros are built on the #define preprocessor. Normally a macro would look like:
#define square(x) x*x
Its arguments substituted for replacement text, when the macro is expanded.
www.cppforschool.com

Pointer

Accessing address of a variable


Computer‟s memory is organized as a linear collection of bytes. Every byte in
the computer‟s memory has an address. Each variable in program is stored at a
unique address. We can use address operator & to get address of a variable:
int num = 23;
cout << &num; // prints address in hexadecimal

POINTER
A pointer is a variable that holds a memory address, usually the location of
another variable in memory.

Defining a Pointer Variable


int *iptr;
iptr can hold the address of an int

Pointer Variables Assignment:


int num = 25;
int *iptr;
iptr = &num;

Memory layout

To access num using iptr and indirection operator *


cout << iptr; // prints 0x4a00
cout << *itptr; // prints 25

Similary, following declaration shows:


char *cptr;
float *fptr;
cptr is a pointer to character and fptr is a pointer to float value.
Pointer Arithmetic
Some arithmetic operators can be used with pointers:
- Increment and decrement operators ++, --
- Integers can be added to or subtracted from
pointers using the operators +, -, +=, and -=

Each time a pointer is incremented by 1, it points to the memory location of the


next element of its base type.
If “p” is a character pointer then “p++” will increment “p” by 1 byte.
If “p” were an integer pointer its value on “p++” would be incremented by 4
bytes.

Pointers and Arrays


Array name is base address of array
int vals[] = {4, 7, 11};
cout << vals; // displays 0x4a00
cout << vals[0]; // displays 4

Lets takes an example:

int arr[]={4,7,11};
int *ptr = arr;
What is ptr + 1?
It means (address in ptr) + (1 * size of an int)
cout << *(ptr+1); // displays 7
cout << *(ptr+2); // displays 11

Array Access
Array notation arr[i] is equivalent to the pointer notation *(arr + i)

Assume the variable definitions


int arr[]={4,7,11};
int *ptr = arr;
Examples of use of ++ and --
ptr++; // points at 7
ptr--; // now points at 4
Character Pointers and Strings
Initialize to a character string.
char* a = “Hello”;
a is pointer to the memory location where „H‟ is stored. Here “a” can be viewed
as a character array of size 6, the only difference being that a can be reassigned
another memory location.
char* a = “Hello”;
a gives address of „H‟
*a gives „H‟
a[0] gives „H‟
a++ gives address of „e‟
*a++ gives „e‟

Pointers as Function Parameters


A pointer can be a parameter. It works like a reference parameter to allow
change to argument from within function

#include<iostream>
using namespace std;

void swap(int *, int *);

int main()
{
int a=10,b=20;
swap(&a, &b);
cout<<a<<" "<<b;
return 0;
}
void swap(int *x, int *y)
{
int t;
t=*x;
*x=*y;
*y=t;
}

output:
20 10
Pointers to Constants and Constant Pointers

Pointer to a constant: cannot change the value that is pointed at


Constant pointer: address in pointer cannot change once pointer is initialized

Pointers to Structures
We can create pointers to structure variables

struct Student {int rollno; float fees;};


Student stu1;
Student *stuPtr = &stu1;
(*stuPtr).rollno= 104;
-or-
Use the form ptr->member:
stuPtr->rollno = 104;

Static allocation of memory


In the static memory allocation, the amount of memory to be allocated is
predicted and preknown. This memory is allocated during the compilation itself.
All the declared variables declared normally, are allocated memory statically.

Dynamic allocation of memory


In the dynamic memory allocation, the amount of memory to be allocated is not
known. This memory is allocated during run-time as and when required. The
memory is dynamically allocated using new operator.

Free store
Free store is a pool of unallocated heap memory given to a program that is used
by the program for dynamic allocation during execution.

Dynamic Memory Allocation


We can allocate storage for a variable while program is running by using new
operator
To allocate memory of type integer
int *iptr=new int;

To allocate array
double *dptr = new double[25];

To allocate dynamic structure variables or objects


Student sptr = new Student; //Student is tag name of structure

Releasing Dynamic Memory


Use delete to free dynamic memory
delete iptr;
To free dynamic array memory
delete [] dptr;
To free dynamic structure
delete Student;

Memory Leak
If the objects, that are allocated memory dynamically, are not deleted using
delete, the memory block remains occupied even at the end of the program.
Such memory blocks are known as orphaned memory blocks. These orphaned
memory blocks when increase in number, bring adverse effect on the system.
This situation is called memory leak

Self Referential Structure


The self referential structures are structures that include an element that is a
pointer to another structure of the same type.

struct node
{
int data;
node* next;
}
www.cppforschool.com

Data File Handling in C++


File. The information / data stored under a specific name on a storage device, is
called a file.

Stream. It refers to a sequence of bytes.

Text file. It is a file that stores information in ASCII characters. In text files,
each line of text is terminated with a special character known as EOL (End of
Line) character or delimiter character. When this EOL character is read or
written, certain internal translations take place.

Binary file. It is a file that contains information in the same format as it is held
in memory. In binary files, no delimiters are used for a line and no translations
occur here.

Classes for file stream operation


ofstream: Stream class to write on files
ifstream: Stream class to read from files
fstream: Stream class to both read and write from/to files.

Opening a file
OPENING FILE USING CONSTRUCTOR
ofstream outFile("sample.txt"); //output only
ifstream inFile(“sample.txt”); //input only

OPENING FILE USING open()


Stream-object.open(“filename”, mode)

ofstream outFile;
outFile.open("sample.txt");

ifstream inFile;
inFile.open("sample.txt");
File mode parameter Meaning
ios::app Append to end of file
ios::ate go to end of file on opening
ios::binary file open in binary mode
ios::in open file for reading only
ios::out open file for writing only
ios::nocreate open fails if the file does not exist
ios::noreplace open fails if the file already exist
ios::trunc delete the contents of the file if it exist

All these flags can be combined using the bitwise operator OR (|). For example,
if we want to open the file example.bin in binary mode to add data we could do
it by the following call to member function open():

fstream file;
file.open ("example.bin", ios::out | ios::app | ios::binary);

Closing File
outFile.close();
inFile.close();

INPUT AND OUTPUT OPERATION

put() and get() function


the function put() writes a single character to the associated stream. Similarly,
the function get() reads a single character form the associated stream.
example :
file.get(ch);
file.put(ch);

write() and read() function


write() and read() functions write and read blocks of binary data.
example:
file.read((char *)&obj, sizeof(obj));
file.write((char *)&obj, sizeof(obj));
ERROR HANDLING FUNCTION

FUNCTION RETURN VALUE AND MEANING

returns true (non zero) if end of file is


eof() encountered while reading; otherwise return
false(zero)

return true when an input or output operation


fail()
has failed

returns true if an invalid operation is attempted


bad()
or any unrecoverable error has occurred.

good() returns true if no error has occurred.

File Pointers and Their Manipulation


All i/o streams objects have, at least, one internal stream pointer:
ifstream, like istream, has a pointer known as the get pointer that points to the
element to be read in the next input operation.

ofstream, like ostream, has a pointer known as the put pointer that points to
the location where the next element has to be written.

Finally, fstream, inherits both, the get and the put pointers, from iostream
(which is itself derived from both istream and ostream).

These internal stream pointers that point to the reading or writing locations
within a stream can be manipulated using the following member functions:

seekg() moves get pointer(input) to a specified location

seekp() moves put pointer (output) to a specified location

tellg() gives the current position of the get pointer

tellp() gives the current position of the put pointer


The other prototype for these functions is:

seekg(offset, refposition );
seekp(offset, refposition );

The parameter offset represents the number of bytes the file pointer is to be
moved from the location specified by the parameter refposition. The refposition
takes one of the following three constants defined in the ios class.

ios::beg start of the file


ios::cur current position of the pointer
ios::end end of the file

example:
file.seekg(-10, ios::cur);
www.cppforschool.com

Basic Operation On Text File In C++


File I/O is a five-step process:
1. Include the header file fstream in the program.
2. Declare file stream object.
3. Open the file with the file stream object.
4. Use the file stream object with >>, <<, or other input/output functions.
5. Close the files.

Following program shows how the steps might appear in program.

Program to write in a text file

#include <fstream>
using namespace std;

int main()
{
ofstream fout;
fout.open("out.txt");

char str[300] = "Time is a great teacher but


unfortunately it kills all its pupils. Berlioz";

//Write string to the file.


fout << str;

fout.close();
return 0;
}

Program to read from text file and display it

#include<fstream>
#include<iostream>
using namespace std;

int main()
{
ifstream fin;
fin.open("out.txt");

char ch;

while(!fin.eof())
{
fin.get(ch);
cout << ch;
}

fin.close();
return 0;
}

Program to count number of characters.

#include<fstream>
#include<iostream>
using namespace std;

int main()
{
ifstream fin;
fin.open("out.txt");

int count = 0;
char ch;

while(!fin.eof())
{
fin.get(ch);
count++;
}

cout << "Number of characters in file are " << count;

fin.close();
return 0;
}
Program to count number of words
#include<fstream>
#include<iostream>
using namespace std;

int main()
{
ifstream fin;
fin.open("out.txt");

int count = 0;
char word[30];

while(!fin.eof())
{
fin >> word;
count++;
}

cout << "Number of words in file are " << count;

fin.close();
return 0;
}

Program to count number of lines

#include<fstream>
#include<iostream>
using namespace std;

int main()
{
ifstream fin;
fin.open("out.txt");

int count = 0;
char str[80];

while(!fin.eof())
{
fin.getline(str,80);
count++;
}

cout << "Number of lines in file are " << count;


fin.close();
return 0;
}

Program to copy contents of file to another file.

#include<fstream>
using namespace std;

int main()
{
ifstream fin;
fin.open("out.txt");

ofstream fout;
fout.open("sample.txt");

char ch;

while(!fin.eof())
{
fin.get(ch);
fout << ch;
}

fin.close();
return 0;
}

Basic Operation on Binary File In C++


When data is stored in a file in the binary format, reading and writing
data is faster because no time is lost in converting the data from one format to
another format. Such files are called binary files. This following program
explains how to create binary files and also how to read, write, search, delete
and modify data from binary files.

#include<iostream>
#include<fstream>
#include<cstdio>
using namespace std;

class Student
{
int admno;
char name[50];
public:
void setData()
{
cout << "\nEnter admission no. ";
cin >> admno;
cout << "Enter name of student ";
cin.getline(name,50);
}

void showData()
{
cout << "\nAdmission no. : " << admno;
cout << "\nStudent Name : " << name;
}

int retAdmno()
{
return admno;
}
};

/*
* function to write in a binary file.
*/

void write_record()
{
ofstream outFile;
outFile.open("student.dat", ios::binary | ios::app);

Student obj;
obj.setData();

outFile.write((char*)&obj, sizeof(obj));

outFile.close();
}

/*
* function to display records of file
*/
void display()
{
ifstream inFile;
inFile.open("student.dat", ios::binary);

Student obj;

while(inFile.read((char*)&obj, sizeof(obj)))
{
obj.showData();
}

inFile.close();
}

/*
* function to search and display from binary file
*/

void search(int n)
{
ifstream inFile;
inFile.open("student.dat", ios::binary);

Student obj;

while(inFile.read((char*)&obj, sizeof(obj)))
{
if(obj.retAdmno() == n)
{
obj.showData();
}
}

inFile.close();
}

/*
* function to delete a record
*/

void delete_record(int n)
{
Student obj;
ifstream inFile;
inFile.open("student.dat", ios::binary);

ofstream outFile;
outFile.open("temp.dat", ios::out | ios::binary);

while(inFile.read((char*)&obj, sizeof(obj)))
{
if(obj.retAdmno() != n)
{
outFile.write((char*)&obj, sizeof(obj));
}
}

inFile.close();
outFile.close();

remove("student.dat");
rename("temp.dat", "student.dat");
}

/*
* function to modify a record
*/

void modify_record(int n)
{
fstream file;
file.open("student.dat",ios::in | ios::out);

Student obj;

while(file.read((char*)&obj,sizeof(obj)))
{
if(obj.retAdmno() == n)
{
cout << "\nEnter the new details of student";
obj.setData();

int pos = -1 * sizeof(obj);


file.seekp(pos, ios::cur);

file.write((char*)&obj, sizeof(obj));
}
}

file.close();
}

int main()
{
//Store 4 records in file
for(int i = 1; i <= 4; i++)
write_record();

//Display all records


cout << "\nList of records";
display();

//Search record
cout << "\nSearch result";
search(100);

//Delete record
delete_record(100);
cout << "\nRecord Deleted";

//Modify record
cout << "\nModify Record 101 ";
modify_record(101);

return 0;
}
www.cppforschool.com

OOP Concepts
There are two common programming methods: procedural programming and
object-oriented programming (OOP). So far you have been creating procedural
programs.

Procedural Programming
In a procedural program data is typically stored in a collection of variables and
there is a set of functions that perform operations on the data. The data and the
functions are separate entities. Usually the variables are passed to the functions
that perform the desired operations. As you might imagine, the focus of
procedural programming is on creating the functions, or procedures, that
operate on the program’s data. Procedural programming works well. However,
as programs become larger and more complex, the separation of a program’s
data and the code that operates on the data can lead to problems.

Object Oriented programming


The object oriented programming design models the real world well and
overcomes the shortcomings of procedural paradigm. It views a problem in
terms of objects and thus emphasizes on both procedures as well as data.

An object is an entity that combines both data and procedures in a single unit.
An object’s data items, also referred to as its attributes, are stored in member
variables. The procedures that an object performs are called its member
functions. This wrapping of an object’s data and procedures together is called
encapsulation.

Not only objects encapsulate associated data and procedures, they also permit
data hiding. Data hiding refers to an object’s ability to hide its data from code
outside the object. Only the object’s member functions can directly access and
make changes to the object’s data.

Advantages of Object oriented programming.


Software complexity can be easily managed
Object-oriented systems can be easily upgraded
It is quite easy to partition the work in a project based on object.
www.cppforschool.com

Class & Objects


The mechanism that allows you to combine data and the function in a single
unit is called a class. Once a class is defined, you can declare variables of that
type. A class variable is called object or instance. In other words, a class would
be the data type, and an object would be the variable. Classes are generally
declared using the keyword class, with the following format:
class class_name
{
private:
members1;
protected:
members2;
public:
members3;
};

Where class_name is a valid identifier for the class. The body of the declaration
can contain members, that can be either data or function declarations, The
members of a class are classified into three categories: private, public, and
protected. private, protected, and public are reserved words and are called
member access specifiers. These specifiers modify the access rights that the
members following them acquire.

private members of a class are accessible only from within other members of
the same class. You cannot access it outside of the class.
protected members are accessible from members of their same class and also
from members of their derived classes.
Finally, public members are accessible from anywhere where the object is
visible.

By default, all members of a class declared with the class keyword have private
access for all its members. Therefore, any member that is declared before one
other class specifier automatically has private access.

Here is a complete example :


class Circle
{
private:
double radius;
public:
void setRadius(double r)
{
radius = r;
}
double getArea()
{
return 3.14 * radius * radius;
}
};

Object Declaration
Once a class is defined, you can declare objects of that type. The syntax for
declaring a object is the same as that for declaring any other variable. The
following statements declare two objects of type circle:
Circle c1, c2;

Accessing Class Members


Once an object of a class is declared, it can access the public members of the
class.
c1.setRadius(2.5);

Defining Member function of class


You can define Functions inside the class as shown in above example. Member
functions defined inside a class this way are created as inline functions by
default. It is also possible to declare a function within a class but define it
elsewhere. Functions defined outside the class are not normally inline.
When we define a function outside the class we cannot reference them (directly)
outside of the class. In order to reference these, we use the scope resolution
operator, :: (double colon). In this example, we are defining function setRadius
outside the class:
void Circle :: setRadius(double r)
{
radius = r;
}

The following program demonstrates the general feature of classes. Member


functions setRadius() and getArea() defined outside the class.

#include <iostream>
using namespace std;

class Circle //specify a class


{
private :
double radius; //class data members
public:
void setRadius(double r);
double getArea(); //member function to return area
};

void Circle :: setRadius(double r)


{
radius = r;
}

double Circle :: getArea()


{
return 3.14 * radius * radius;
}

int main()
{
Circle c1; //define object of class circle
c1.setRadius(2.5); //call member function to initialize radius
cout << c1.getArea(); //display area of circle object
return 0;
}
www.cppforschool.com

Constructor and Destructor

Constructor
It is a member function having same name as it’s class and which is used to
initialize the objects of that class type with a legal initial value. Constructor is
automatically called when object is created.

Types of Constructor
Default Constructor-: A constructor that accepts no parameters is known as
default constructor. If no constructor is defined then the compiler supplies a
default constructor.
Circle :: Circle()
{
radius = 0;
}

Parameterized Constructor -: A constructor that receives


arguments/parameters, is called parameterized constructor.
Circle :: Circle(double r)
{
radius = r;
}

Copy Constructor-: A constructor that initializes an object using values of


another object passed to it as parameter, is called copy constructor. It creates
the copy of the passed object.
Circle :: Circle(Circle &t)
{
radius = t.radius;
}

There can be multiple constructors of the same class, provided they


have different signatures.
Destructor
A destructor is a member function having sane name as that of its class
preceded by ~(tilde) sign and which is used to destroy the objects that have
been created by a constructor. It gets invoked when an object’s scope is over.
~Circle() {}

Example : In the following program constructors, destructor and other


member functions are defined inside class definitions. Since we are using
multiple constructor in class so this example also illustrates the concept of
constructor overloading
#include<iostream>
using namespace std;

class Circle //specify a class


{
private :
double radius; //class data members
public:
Circle() //default constructor
{
radius = 0;
}
Circle(double r) //parameterized constructor
{
radius = r;
}
Circle(Circle &t) //copy constructor
{
radius = t.radius;
}
void setRadius(double r) //function to set data
{
radius = r;
}
double getArea()
{
return 3.14 * radius * radius;
}
~Circle() //destructor
{}
};

int main()
{
Circle c1; //default constructor invoked
Circle c2(2.5); //parmeterized constructor invoked
Circle c3(c2); //copy constructor invoked
cout << c1.getArea()<<endl;
cout << c2.getArea()<<endl;
cout << c3.getArea()<<endl;
return 0;
}

Another way of Member initialization in constructors

The constructor for this class could be defined, as usual, as:


Circle :: Circle(double r)
{
radius = r;
}

It could also be defined using member initialization as:


Circle :: Circle(double r) : radius(r)
{}
www.cppforschool.com

Time Class Case Study


In the preceding section, we introduced many basic terms and concepts of C++
object oriented programming. In this section, we take a deeper look at classes.
In this Time class case study we will demonstrate several class construction
features. We begin with a Time class that reviews several of the features
presented in the preceding section.

#include<iostream>
#include<iomanip>
using namespace std;

class Time
{
private :
int hour;
int minute;
int second;
public :
//constructor with default value 0
Time(int h = 0, int m = 0, int s = 0);
//setter function
void setTime(int h, int m, int s);
//print description of object in hh:mm:ss
void print();
//compare two time object
bool equals(Time);
};

Time :: Time(int h, int m, int s)


{
hour = h;
minute = m;
second = s;
}

void Time :: setTime(int h, int m, int s)


{
hour = h;
minute = m;
second = s;
}
void Time :: print()
{
cout << setw(2) << setfill('0') << hour << ":"
<< setw(2) << setfill('0') << minute << ":"
<< setw(2) << setfill('0') << second << "\n";
}

bool Time :: equals(Time otherTime)


{
if(hour == otherTime.hour &&
minute == otherTime.minute &&
second == otherTime.second)
return true;
else
return false;
}

int main()
{
Time t1(10, 50, 59);
t1.print(); // 10:50:59
Time t2; //object created with default value
t2.print(); // 00:00:00
t2.setTime(6, 39, 9); //set the new time in object
t2.print(); // 06:39:09

if(t1.equals(t2))
cout << "Two objects are equals\n";
else
cout << "Two objects are not equals\n";

return 0;
}

Output :

10:50:59
00:00:00
06:39:09
Two objects are not equals

Let's us discuss our Time class and add some new concepts of programming
Constructors with Default Arguments

In Circle class we have created explicit default constructor and parameterized


constructor. Compiler overloads constructor based on match.

You can combine both statements in one as in Time class example

//constructor with default value


Time(int h = 0, int m = 0, int s = 0);

It works same way just matter of styling code.

Constant Function

In some cases, you will need that the member function should not change any
private member variables of the calling object. You can do this by adding const
to the end of the function declaration (prototype) and in the function definition.

Let’s make member functions in our Time class const if appropriate:

class Time
{
...
...
//print description of object in hh:mm:ss
void print() const;
...
...

};

....
....
void Time :: print() const
{
cout << setw(2) << setfill('0') << hour << ":"
<< setw(2) << setfill('0') << minute << ":"
<< setw(2) << setfill('0') << second << "\n";
}

....
Constant Parameters

You can make a parameter in a function as being a const parameter by


preceding its type with const. This tells the compiler to disallow that parameter
changing its value inside that function. This mechanism protects you from
making inadvertent mistakes.

Let’s make parameter constant in our Time class, if appropriate:


class Time
{
.....
//constructor with default value 0
Time(const int h = 0, const int m = 0, const int s = 0);
//setter function
void setTime(const int h, const int m, const int s);
.....
};

Time :: Time(const int h, const int m, const int s)


{
hour = h;
minute = m;
second = s;
}

void Time :: setTime(const int h, const int m, const int s)


{
hour = h;
minute = m;
second = s;
}

......

Passing Objects to Functions

Object can be passed by value, by reference or by pointer. In our Time class we


passed object by value.
bool Time :: equals(Time otherTime)
{
if(hour == otherTime.hour &&
minute == otherTime.minute &&
second == otherTime.second)
return true;
else
return false;
}

This means that equals() receives a copy of object t2 with name otherTime.
If a function needs to store or change data in an object’s member variables, the
object must be passed to it by reference.

Constant Reference Parameters

Passing by const reference is the preferred way to pass objects as an alternative


to pass-by-value. When you pass by const reference, you take the argument in
by reference, but cannot make any changes to the original object.
//object passing by reference with const parameter
bool equals(const Time&);
www.cppforschool.com

Separate Header and Implementation Files


In this section, we demonstrate how to make class reusable by separating it
into other files.

Header File

Class declarations are stored in a separate file. A file that contains a class
declaration is called header file. The name of the class is usually the same as
the name of the class, with a .h extension. For example, the Time class would
be declared in the file Time .h.

#ifndef TIME_H
#define TIME_H

class Time
{
private :
int hour;
int minute;
int second;
public :
//with default value
Time(const int h = 0, const int m = 0, const int s = 0);
// setter function
void setTime(const int h, const int m, const int s);
// Print a description of object in " hh:mm:ss"
void print() const;
//compare two time object
bool equals(const Time&);
};

#endif
Implementation File

The member function definitions for a class are stored in a separate .cpp file,
which is called the class implementation file. The file usually has the same name
as the class, with the .cpp extension. For example the Time class member
functions would be defined in the file Time.cpp.

#include <iostream>
#include <iomanip>
#include "Time.h"
using namespace std;

Time :: Time(const int h, const int m, const int s)


: hour(h), minute (m), second(s)
{}

void Time :: setTime(const int h, const int m, const int s)


{
hour = h;
minute = m;
second = s;
}

void Time :: print() const


{
cout << setw(2) << setfill('0') << hour << ":"
<< setw(2) << setfill('0') << minute << ":"
<< setw(2) << setfill('0') << second << "\n";

bool Time :: equals(const Time &otherTime)


{
if(hour == otherTime.hour
&& minute == otherTime.minute
&& second == otherTime.second)
return true;
else
return false;
}
Client Code

Client code, is the one that includes the main function. This file should be stored
by the name main.cpp

#include <iostream>
using namespace std;
#include "Time.h"

int main()
{
Time t1(10, 50, 59);
t1.print(); // 10:50:59
Time t2;
t2.print(); // 06:39:09
t2.setTime(6, 39, 9);
t2.print(); // 06:39:09

if(t1.equals(t2))
cout << "Two objects are equal\n";
else
cout << "Two objects are not equal\n";

return 0;
}

The advantages of storing class definition in separate file are

1. The class is reusable.

2. The clients of the class know what member functions the class provides, how
to call them and what return types to expect.

3. The clients do not know how the class's member functions are implemented.
www.cppforschool.com

Static Members of a Class


In the previous sections we have shown examples of classes where each object
of a class had its own set of data. Member function could access the object's
own version of the data.

In some situations it may be desirable that one or more common data fields
should exist, which are accessible to all objects of the class. In C++, a static
member is shared by all objects of the class.

Static Data Members

A data member of a class can be declared static; be it in the public or private


part of the class definition. Such a data member is created and initialized only
once. Static data members which are declared public can be accessed by using
class name and the scope resolution operator.

We only include the declaration of static data in the class declaration.


Initialization of a static data-member is done outside the class. This is
illustrated in the following code fragment:

#include <iostream>
using namespace std;

class Circle
{
private:
double radius; // Radius of a circle
public:
static int count;
// Constructor definition
Circle(double r = 1.0)
{
radius = r;
// Increase every time object is created
count++;
}
double getArea()
{
return 3.14 * radius * radius;
}
};
// Initialize static member of class Circle
int Circle::count = 0;

int main()
{
Circle c1(3.3); // Declare object c1
Circle c2(4.5); // Declare object c2

// Print total number of objects.


cout << "Total objects: " << Circle::count << endl;

return 0;
}

Output:

Total objects: 2

Static Member Functions

The static functions can access only the static data of a class. Similarly, static
functions cannot call non-static functions of the class.

Functions which are static and which are declared in the public section of a class
can be called without specifying an object of the class. This is illustrated in the
following code fragment:

#include <iostream>
using namespace std;

class Circle
{
private:
static int count;
double radius; // Radius of a circle
public:
// Constructor definition
Circle(double r = 1.0)
{
radius = r;
// Increase every time object is created
count++;
}
double getArea()
{
return 3.14 * radius * radius;
}
static int getCount()
{
return count;
}
};

// Initialize static member of class Circle


int Circle::count = 0;

int main()
{
Circle c1(3.3); // Declare object c1
Circle c2(4.5); // Declare object c2

// Print total number of objects.


cout << "Total objects: " << Circle::getCount() << endl;

return 0;
}

Output:

Total objects: 2
www.cppforschool.com

Friend Functions
As we have seen in the previous sections, private and protected data or function
members are normally only accessible by the code which is part of same class.
However, situations may arise in which it is desirable to allow the explicit access
to private members of class to other functions.

If we want to declare an external function as friend of a class, thus allowing this


function to have access to the private and protected members of this class, we
do it by declaring a prototype of this external function within the class, and
preceding it with the keyword friend. This is illustrated in the following code
fragment:

#include <iostream>
using namespace std;

class Rectangle
{
private :
int length;
int width;
public:

void setData(int len, int wid)


{
length = len;
width = wid;
}

int getArea()
{
return length * width ;
}

friend double getCost(Rectangle); //friend of class Rectangle


};

//friend function getCost can access private member of class


double getCost (Rectangle rect)
{
double cost;
cost = rect.length * rect.width * 5;
return cost;
}
int main ()
{
Rectangle floor;
floor.setData(20,3);
cout << "Expense " << getCost(floor) << endl;
return 0;
}

Output :
Expense 300

The getCost function is a friend of Rectangle. From within that function we have
been able to access the members length and width, which are private members.

Friend Classes
One class member function can access the private and protected members of
other class. We do it by declaring a class as friend of other class. This is
illustrated in the following code fragment:

#include <iostream>
using namespace std;

class CostCalculator;

class Rectangle
{
private :
int length;
int width;
public:
void setData(int len, int wid)
{
length = len;
width = wid;
}

int getArea()
{
return length * width ;
}

friend class CostCalculator; //friend of class Rectangle


};
//friend class costCalculator can access private member of class
Rectangle

class CostCalculator
{
public :
double getCost (Rectangle rect)
{
double cost;
cost = rect.length * rect.width * 5;
return cost;
}
};

int main ()
{
Rectangle floor;
floor.setData(20,3);
CostCalculator calc;
cout << "Expense " << calc.getCost(floor) << endl;
return 0;
}

Output :
Expense 300

Note : An empty declaration of class costCalculator at top is necessary.


www.cppforschool.com

Operator Overloading in C++


Operator overloading is giving new functionality to an existing operator. It
means the behavior of operators when applied to objects of a class can be
redefined. It is similar to overloading functions except the function name is
replaced by the keyword operator followed by the operator’s symbol. There are
5 operators that are forbidden to overload. They are :: . .* sizeof ?:

In the following code fragment, we will overload binary + operator for Complex
number class object.

#include <iostream>
using namespace std;

class Complex
{
private :
double real;
double imag;
public:
Complex () {};
Complex (double, double);
Complex operator + (Complex);
void print();
};

Complex::Complex (double r, double i)


{
real = r;
imag = i;
}

Complex Complex::operator+ (Complex param)


{
Complex temp;
temp.real = real + param.real;
temp.imag = imag + param.imag;
return (temp);
}

void Complex::print()
{
cout << real << " + i" << imag << endl;
}
int main ()
{
Complex c1 (3.1, 1.5);
Complex c2 (1.2, 2.2);
Complex c3;

c3 = c1 + c2; //use overloaded + operator

c1.print();
c2.print();
c3.print();
return 0;
}

Output :
3.1 + i1.5
1.2 + i2.2
4.3 + i3.7

In C++ we can cause an operator to invoke a member function by giving that


member function a special name (of the form: operator<symbol>). Hence for
the sum operation, the special name is: operator+. So, by naming the member
function operator+ we can call the function by statement
c3 = c1 + c2

That is similiar to
c3 = c1.operator+(c2);
www.cppforschool.com

Inheritance
The mechanism that allows us to extend the definition of a class without making
any physical changes to the existing class is inheritance.

Inheritance lets you create new classes from existing class. Any new class that
you create from an existing class is called derived class; existing class is called
base class.

The inheritance relationship enables a derived class to inherit features from its
base class. Furthermore, the derived class can add new features of its own.
Therefore, rather than create completely new classes from scratch, you can
take advantage of inheritance and reduce software complexity.

Forms of Inheritance

Single Inheritance: It is the inheritance hierarchy wherein one derived class


inherits from one base class.

Multiple Inheritance: It is the inheritance hierarchy wherein one derived class


inherits from multiple base class(es)

Hierarchical Inheritance: It is the inheritance hierarchy wherein multiple


subclasses inherit from one base class.

Multilevel Inheritance: It is the inheritance hierarchy wherein subclass acts


as a base class for other classes.

Hybrid Inheritance: The inheritance hierarchy that reflects any legal


combination of other four types of inheritance.
In order to derive a class from another, we use a colon (:) in the declaration of
the derived class using the following format :

class derived_class: memberAccessSpecifier base_class


{
...
};

Where derived_class is the name of the derived class and base_class is the
name of the class on which it is based. The member Access Specifier may be
public, protected or private. This access specifier describes the access level for
the members that are inherited from the base class.
Member How Members of the Base Class Appear in the
Access Derived Class
Specifier

Private Private members of the base class are inaccessible


to the derived class.

Protected members of the base class become private


members of the derived class.

Public members of the base class become private


members of the derived class.

Protected Private members of the base class are inaccessible


to the derived class.

Protected members of the base class become


protected members of the derived class.

Public members of the base class become protected


members of the derived class.

Public Private members of the base class are inaccessible


to the derived class.

Protected members of the base class become


protected members of the derived class.

Public members of the base class become public


members of the derived class.

In principle, a derived class inherits every member of a base class except


constructor and destructor. It means private members are also become
members of derived class. But they are inaccessible by the members of
derived class.
Following example further explains concept of inheritance :

class Shape
{
protected:
float width, height;
public:
void set_data (float a, float b)
{
width = a;
height = b;
}
};

class Rectangle: public Shape


{
public:
float area ()
{
return (width * height);
}
};

class Triangle: public Shape


{
public:
float area ()
{
return (width * height / 2);
}
};
int main ()
{
Rectangle rect;
Triangle tri;
rect.set_data (5,3);
tri.set_data (2,5);
cout << rect.area() << endl;
cout << tri.area() << endl;
return 0;
}

output :

15
5

The object of the class Rectangle contains :


width, height inherited from Shape becomes the protected member of
Rectangle.

set_data() inherited from Shape becomes the public member of Rectangle


area is Rectangle’s own public member

The object of the class Triangle contains :


width, height inherited from Shape becomes the protected member of Triangle.
set_data() inherited from Shape becomes the public member of Triangle
area is Triangle’s own public member

set_data () and area() are public members of derived class and can be accessed
from outside class i.e. from main()
www.cppforschool.com

Constructor and inheritance


The compiler automatically calls a base class constructor before executing the
derived class constructor. The compiler’s default action is to call the default
constructor in the base class. You can specify which of several base class
constructors should be called during the creation of a derived class object.

This is done by specifying the arguments to the selected base class constructor
in the definition of the derived class constructor.

class Rectangle
{
private :
float length;
float width;
public:
Rectangle ()
{
length = 0;
width = 0;
}

Rectangle (float len, float wid)


{
length = len;
width = wid;
}

float area()
{
return length * width ;
}
};

class Box : public Rectangle


{
private :
float height;
public:
Box ()
{
height = 0;
}
Box (float len, float wid, float ht) : Rectangle(len, wid)
{
height = ht;
}

float volume()
{
return area() * height;
}
};

int main ()
{
Box bx;
Box cx(4,8,5);
cout << bx.volume() << endl;
cout << cx.volume() << endl;
return 0;
}

output :

0
160

Overriding Base Class Functions

A derived class can override a member function of its base class by defining a
derived class member function with the same name and parameter list.
It is often useful for a derived class to define its own version of a member
function inherited from its base class. This may be done to specialize the
member function to the needs of the derived class. When this happens, the
base class member function is said to be overridden by the derived class.
class mother
{
public:
void display ()
{
cout << "mother: display function\n";
}
};

class daughter : public mother


{
public:
void display ()
{
cout << "daughter: display function\n\n";
}
};

int main ()
{
daughter rita;
rita.display();
return 0;
}

output:
daughter: display function

Gaining Access to an Overridden Function

It is occasionally useful to be able to call the overridden version. This is done by


using the scope resolution operator to specify the class of the overridden
member function being accessed.

class daughter : public mother


{
public:
void display ()
{
cout << "daughter: display function\n\n";
mother::display();
}
};
output:

daughter: display function

mother: display function

Virtual Base Class

Multipath inheritance may lead to duplication of inherited members from a


grandparent base class. This may be avoided by making the common base class
a virtual base class. When a class is made a virtual base class, C++ takes
necessary care to see that only one copy of that class is inherited.

class A
{
.....
.....
};

class B1 : virtual public A


{
.....
.....
};

class B2 : virtual public A


{
.....
.....
};

class C : public B1, public B2


{
.....// only one copy of A
.....// will be inherited
};
www.cppforschool.com

Polymorphism, Virtual Functions and Abstract Class


In C++, a pointer variable of a base class type can point to an object of its derived
class. There are situations when this feature of C++ can be used to develop generic
code for a variety of applications.

Pointer of base class


Consider the following program to understand pointer compatibility property
#include <iostream>
using namespace std;

class Shape
{
protected:
double width, height;
public:
void set_data (double a, double b)
{
width = a;
height = b;
}
};

class Rectangle: public Shape


{
public:
double area ()
{
return (width * height);
}
};

int main ()
{
Shape *sPtr; //declare pointer variables of type Shape
Rectangle Rect; //create the object rect of type Rectangle
sPtr = &Rect; //make sPtr point to the object rect.

sPtr->set_data (5,3); //set length and width of object rect


cout << sPtr -> area() << endl; //Compile Error !!

return 0;
}
Notice that even though rectPtr is pointing to rect (object of type Rectangle), when
the program executes, the statement sets length and width of rectangle. If you tried
to access area function of class Rectangle with sPtr it will give you compiler error.
sPtr -> area()

is a compiler error !

It means base class pointer can not access the additional member function of
its derived class. If we want to do this we need to type cast the base class pointer.

Using Type Casts with Base Class Pointers


We can use a type cast to get the compiler to accept the statement:
static_cast <Rectangle *> (sPtr)->area()

so we should write the statment


cout << static_cast <Rectangle *> (sPtr) -> area() << endl;

The type cast informs the compiler that sPtr is actually pointing to a Rectangle object
derived from the Shape base class. In general, a pointer to a base class that
actually points to a derived class object must first be appropriately cast
before the additional features of the derived class can be used.

Virtual Function and Polymorphism


Virtual functions are used in C++ to support polymorphic behavior. We are modifing
the above program and will introduce you the concept of virtual function by following
example:
#include <iostream>
using namespace std;

class Shape
{
protected:
double width, height;
public:
void set_data (double a, double b)
{
width = a;
height = b;
}
virtual double area()
{return 0;}
};

class Rectangle: public Shape


{
public:
double area ()
{
return (width * height);
}
};

int main ()
{
Shape *sPtr;
Rectangle Rect;
sPtr = &Rect;

sPtr -> set_data (5,3);


cout << sPtr -> area() << endl;

return 0;
}

Output :
15

A member of a class that can be redefined in its derived classes is known as a virtual
member. In order to declare a member of a class as virtual, we must precede its
declaration with the keyword virtual. The member function area() has been declared
as virtual in the base class because it is later redefined in each
derived class. The advantage of having virtual function is that we are able to
access area function of derived class by pointer variable of base class.

Pure Virtual Function and Abstract Class


In above example, base class Shape member function area do not need any
implementation because it is overriding in derived class. If this is the case, the C++
language permits the programmer to declare the function a pure virtual function. The
C++ way of declaring a pure virtual function is to put the expression = 0 in the class
declaration. For example, if a member function double area() is being declared pure
virtual, then its declaration in its class looks like
virtual double area() = 0;
A pure virtual function is sometimes called an abstract function, and a class with at
least one pure virtual function is called an abstract class. The C++ compiler will not
allow you to instantiate an abstract class. Abstract classes can only be subclassed:
that is, you can only use them as base classes from which to derive other classes.

A class derived from an abstract class inherits all functions in the base class, and will
itself be an abstract class unless it overrides all the abstract functions it inherits. The
usefulness of abstract classes lies in the fact that they define an interface that will
then have to be supported by objects of all classes derived from it.

#include <iostream>
using namespace std;

class Shape
{
protected:
double width, height;
public:
void set_data (double a, double b)
{
width = a;
height = b;
}
virtual double area() = 0;
};

class Rectangle: public Shape


{
public:
double area ()
{
return (width * height);
}
};

class Triangle: public Shape


{
public:
double area ()
{
return (width * height)/2;
}
};

int main ()
{
Shape *sPtr;

Rectangle Rect;
sPtr = &Rect;

sPtr -> set_data (5,3);


cout << "Area of Rectangle is " << sPtr -> area() << endl;

Triangle Tri;
sPtr = &Tri;

sPtr -> set_data (4,6);


cout << "Area of Triangle is " << sPtr -> area() << endl;
return 0;
}

Output :
Area of Rectangle is 15
Area of Triangle is 12
C++ EXCEPTION HANDLING
http://www.tutorialspoint.com/cplusplus/cpp_exceptions_handling.htm Copyright © tutorialspoint.com

An exception is a problem that arises during the execution of a program. A C++ exception is a
response to an exceptional circumstance that arises while a program is running, such as an
attempt to divide by zero.

Exceptions provide a way to transfer control from one part of a program to another. C++
exception handling is built upon three keywords: try, catch, and throw.

throw: A program throws an exception when a problem shows up. This is done using a
throw keyword.

catch: A program catches an exception with an exception handler at the place in a program
where you want to handle the problem. The catch keyword indicates the catching of an
exception.

try: A try block identifies a block of code for which particular exceptions will be activated.
It's followed by one or more catch blocks.

Assuming a block will raise an exception, a method catches an exception using a combination of
the try and catch keywords. A try/catch block is placed around the code that might generate an
exception. Code within a try/catch block is referred to as protected code, and the syntax for using
try/catch looks like the following:

try
{
// protected code
}catch( ExceptionName e1 )
{
// catch block
}catch( ExceptionName e2 )
{
// catch block
}catch( ExceptionName eN )
{
// catch block
}

You can list down multiple catch statements to catch different type of exceptions in case your try
block raises more than one exception in different situations.

Throwing Exceptions:
Exceptions can be thrown anywhere within a code block using throw statements. The operand of
the throw statements determines a type for the exception and can be any expression and the type
of the result of the expression determines the type of exception thrown.

Following is an example of throwing an exception when dividing by zero condition occurs:

double division(int a, int b)


{
if( b == 0 )
{
throw "Division by zero condition!";
}
return (a/b);
}

Catching Exceptions:
The catch block following the try block catches any exception. You can specify what type of
exception you want to catch and this is determined by the exception declaration that appears in
parentheses following the keyword catch.
try
{
// protected code
}catch( ExceptionName e )
{
// code to handle ExceptionName exception
}

Above code will catch an exception of ExceptionName type. If you want to specify that a catch
block should handle any type of exception that is thrown in a try block, you must put an ellipsis, ...,
between the parentheses enclosing the exception declaration as follows:

try
{
// protected code
}catch(...)
{
// code to handle any exception
}

The following is an example, which throws a division by zero exception and we catch it in catch
block.

#include <iostream>
using namespace std;

double division(int a, int b)


{
if( b == 0 )
{
throw "Division by zero condition!";
}
return (a/b);
}

int main ()
{
int x = 50;
int y = 0;
double z = 0;

try {
z = division(x, y);
cout << z << endl;
}catch (const char* msg) {
cerr << msg << endl;
}

return 0;
}

Because we are raising an exception of type const char*, so while catching this exception, we
have to use const char* in catch block. If we compile and run above code, this would produce the
following result:

Division by zero condition!

C++ Standard Exceptions:


C++ provides a list of standard exceptions defined in <exception> which we can use in our
programs. These are arranged in a parent-child class hierarchy shown below:
Here is the small description of each exception mentioned in the above hierarchy:

Exception Description

std::exception An exception and parent class of all the standard C++ exceptions.

std::bad_alloc This can be thrown by new.

std::bad_cast This can be thrown by dynamic_cast.

std::bad_exception This is useful device to handle unexpected exceptions in a C++


program

std::bad_typeid This can be thrown by typeid.

std::logic_error An exception that theoretically can be detected by reading the code.

std::domain_error This is an exception thrown when a mathematically invalid domain is


used

std::invalid_argument This is thrown due to invalid arguments.

std::length_error This is thrown when a too big std::string is created

std::out_of_range This can be thrown by the at method from for example a std::vector and
std::bitset<>::operator[].

std::runtime_error An exception that theoretically can not be detected by reading the


code.

std::overflow_error This is thrown if a mathematical overflow occurs.

std::range_error This is occured when you try to store a value which is out of range.

std::underflow_error This is thrown if a mathematical underflow occurs.


Define New Exceptions:
You can define your own exceptions by inheriting and overriding exception class functionality.
Following is the example, which shows how you can use std::exception class to implement your
own exception in standard way:

#include <iostream>
#include <exception>
using namespace std;

struct MyException : public exception


{
const char * what () const throw ()
{
return "C++ Exception";
}
};

int main()
{
try
{
throw MyException();
}
catch(MyException& e)
{
std::cout << "MyException caught" << std::endl;
std::cout << e.what() << std::endl;
}
catch(std::exception& e)
{
//Other errors
}
}

This would produce the following result:

MyException caught
C++ Exception

Here, what is a public method provided by exception class and it has been overridden by all the
child exception classes. This returns the cause of an exception.
Loading [MathJax]/jax/output/HTML-CSS/jax.js

You might also like