Comp 215 - Inte 215-Cosf 223 - Oop With C++ Class Notes
Comp 215 - Inte 215-Cosf 223 - Oop With C++ Class Notes
Control Statements
If, If..Else-If Statement
Switch Case In C++
For Loop
While Loop
Do While Loop
Continue Statement
Break Statement
Goto Statement
Functions
Functions in C++
Default arguments in Functions
C++ Recursion
Arrays
Arrays
Multidimensional arrays
Passing Array to function
C++ Strings
Pointers
Pointers in C++
This Pointer
OOPs
OOPs Concepts
Constructor
Destructor
Structure
How to pass and return struct from function
Enumeration
Inheritance
Polymorphism
Function Overloading
Function Overriding
Virtual Function: Run time Polymorphism
Encapsulation
Abstraction
Interfaces – Abstract class
Pass and return object from function
Friend class and friend Function
After exploring C++ features, let's have a look at some interesting areas where C++ is
popularly used.
Operating Systems
Be it Microsoft Windows or Mac OSX or Linux - all of them are programmed in C++. C/C++
is the backbone of all the well-known operating systems owing to the fact that it is a strongly
typed and a fast programming language which makes it an ideal choice for developing an
operating system. Moreover, C is quite close to the assembly language which further helps in
writing low-level operating system modules.
Browsers
The rendering engines of various web browsers are programmed in C++ simply because if
the speed that it offers. The rendering engines require faster execution to make sure that users
don‘t have to wait for the content to come up on the screen. As a result, such low-latency
systems employ C++ as the programming language.
Libraries
Many high-level libraries use C++ as the core programming language. For instance, several
Machine Learning libraries use C++ in the backend because of its speed. Tensorflow, one of
the most widely used Machine Learning libraries uses C++ as the backend programming
language. Such libraries required high-performance computations because they involve
multiplications of huge matrices for the purpose of training Machine Learning models. As a
result, performance becomes critical. C++ comes to the rescue in such libraries.
Graphics
All graphics applications require fast rendering and just like the case of web browsers, here
also C++ helps in reducing the latency. Software that employ computer vision, digital image
processing, high-end graphical processing - they all use C++ as the backend programming
language. Even the popular games that are heavy on graphics use C++ as the primary
programming language. The speed that C++ offers in such situations helps the developers in
expanding the target audience because an optimized application can run even on low-end
devices that do not have high computation power available.
Banking Applications
One of the most popularly used core-banking system - Infosys Finacle uses C++ as one of the
backend programming languages. Banking applications process millions of transactions on a
daily basis and require high concurrency and low latency support. C++ automatically
becomes the preferred choice in such applications owing to its speed and multithreading
support that is made available through various Standard Template Libraries that come as a
part of the C++ programming kit.
Cloud/Distributed Systems
Large organizations that develop cloud storage systems and other distributed systems also use
C++ because it connects very well with the hardware and is compatible with a lot of
machines. Cloud storage systems use scalable file-systems that work close to the hardware.
C++ becomes a preferred choice in such situations because it is close to the hardware and
also the multithreading libraries in C++ provide high concurrency and load tolerance which is
very much needed in such scenarios.
Databases
Postgres and MySQL - two of the most widely used databases are written in C++ and C, the
precursor to C++. These databases are used in almost all of the well-known applications that
we all use in our day to day life - Quora, YouTube, etc.
Embedded Systems
Various embedded systems like medical machines, smartwatches, etc. use C++ as the primary
programming language because of the fact that C++ is closer to the hardware level as
compared to other high-level programming languages.
Telephone Switches
Because of the fact that it is one of the fastest programming languages, C++ is widely used in
programming telephone switches, routers, and space probes.
Compilers
The compilers of various programming languages use C and C++ as the backend
programming language. This is because of the fact that both C and C++ are relatively lower
level languages and are closer to the hardware and therefore are the ideal choice for such
compilation systems. These are a few uses and applications of C++ programming language.
Now, let's know more about C++ advantages over other programming languages.
/*
* First C++ program that says hello (hello.cpp)
*/
#include <iostream> // Needed to perform IO operations
using namespace std;
#include <iostream>
using namespace std;
int main()
{
int number;
#include <iostream>
using namespace std;
int main()
{
int firstNumber, secondNumber, sumOfTwoNumbers;
// Prints sum
cout << firstNumber << " + " << secondNumber << " = " << sumOfTwoNumbers;
return 0;
}
#include <iostream>
using namespace std;
int main()
{
int divisor, dividend, quotient, remainder;
return 0;
}
#include <iostream>
using namespace std;
int main()
{
int a = 5, b = 10, temp;
return 0;
}
Variables in C++
A variable is a name which is associated with a value that can be changed. For example when
I write int num=20; here variable name is num which is associated with value 20, int is a data
type that represents that this variable can hold integer values. We will cover the data types in
the next tutorial. In this tutorial, we will discuss about variables.
For example:
int num1=20, num2=100;
Types of variables
Variables can be categorised based on their data type. For example, in the above example we
have seen integer types variables. Following are the types of variables available in C++.
int: These type of of variables holds integer value.
char: holds character value like ‗c‘, ‗F‘, ‗B‘, ‗p‘, ‗q‘ etc.
bool: holds boolean value true or false.
double: double-precision floating point value.
float: Single-precision floating point value.
//Some code
Any variable declared inside these curly braces have scope limited within these curly braces,
if you declare a variable in main() function and try to use that variable outside main()
function then you will get compilation error.
Now that we have understood what is scope. Let‘s move on to the types of variables based on
the scope.
Global variable
Local variable
Global Variable
A variable declared outside of any function (including main as well) is called global variable.
Global variables have their scope throughout the program, they can be accessed anywhere in
the program, in the main, in the user defined function, anywhere.
Let‘s take an example to understand it:
Output:
Value of myVar: A
Value of myVar: Z
Local variable
Local variables are declared inside the braces of any user defined function, main function,
loops or any control statements (if, if-else etc) and have their scope limited inside those
braces.
char myFuncn() {
// This is a local variable
char myVar = 'A';
}
int main()
{
cout <<"Value of myVar: "<< myVar<<endl;
myVar='Z';
cout <<"Value of myVar: "<< myVar;
return 0;
}
Output:
Compile time error, because we are trying to access the variable myVar outside of its scope.
The scope of myVar is limited to the body of function myFuncn(), inside those braces.
Output:
Funcn call: B
Value of myVar: A
Funcn call: B
Value of myVar: Z
As you can see that when I changed the value of myVar in the main function, it only changed
the value of global variable myVar because local variable myVar scope is limited to the
function myFuncn().
Struct
Union
Enum
Array
Function
Pointer
Operators in C++
Operator represents an action. For example + is an operator that represents addition. An
operator works on two or more operands and produce an output. For example 3+4+5 here +
operator works on three operands and produce 12 as output.
Output:
num1 + num2: 280
num1 - num2: 200
num1 * num2: 9600
num1 / num2: 6
num1 % num2: 0
2) Assignment Operators
Assignments operators in C++ are: =, +=, -=, *=, /=, %=
num2 = num1 would assign value of variable num1 to the variable.
num2+=num1 is equal to num2 = num2+num1
num2-=num1 is equal to num2 = num2-num1
num2*=num1 is equal to num2 = num2*num1
num2/=num1 is equal to num2 = num2/num1
num2%=num1 is equal to num2 = num2%num1
Output:
= Output: 240
+= Output: 480
-= Output: 240
*= Output: 57600
/= Output: 240
%= Output: 0
Output:
num1++ is: 241
num2-- is: 39
4) Logical Operators
Logical Operators are used with binary variables. They are mainly used in conditional
statements and loops for evaluating a condition.
Logical operators in C++ are: &&, ||, !
Let‘s say we have two boolean variables b1 and b2.
b1&&b2 will return true if both b1 and b2 are true else it would return false.
b1||b2 will return false if both b1 and b2 are false else it would return true.
!b1 would return the opposite of b1, that means it would be true if b1 is false and it would
return false if b1 is true.
Output:
b1 && b2: 0
b1 || b2: 1
!(b1 && b2): 1
5) Relational operators
We have six relational operators in C++: ==, !=, >, <, >=, <=
== returns true if both the left side and right side are equal
!= returns true if left side is not equal to the right side of operator.
> returns true if left side is greater than right.
< returns true if left side is less than right side.
>= returns true if left side is greater than or equal to right side.
<= returns true if left side is less than or equal to right side.
6) Bitwise Operators
There are six bitwise Operators: &, |, ^, ~, <<, >>
num1 = 11; /* equal to 00001011*/
num2 = 22; /* equal to 00010110 */
Bitwise operator performs bit by bit processing.
num1 & num2 compares corresponding bits of num1 and num2 and generates 1 if both bits
are equal, else it returns 0. In our case it would return: 2 which is 00000010 because in the
binary form of num1 and num2 only second last bits are matching.
num1 | num2 compares corresponding bits of num1 and num2 and generates 1 if either bit is
1, else it returns 0. In our case it would return 31 which is 00011111
num1 ^ num2 compares corresponding bits of num1 and num2 and generates 1 if they are
not equal, else it returns 0. In our example it would return 29 which is equivalent to
00011101
~num1 is a complement operator that just changes the bit from 0 to 1 and 1 to 0. In our
example it would return -12 which is signed 8 bit equivalent to 11110100
num1 << 2 is left shift operator that moves the bits to the left, discards the far left bit, and
assigns the rightmost bit a value of 0. In our case output is 44 which is equivalent to
00101100
Note: In the example below we are providing 2 at the right side of this shift operator that is
the reason bits are moving two places to the left side. We can change this number and bits
would be moved by the number of bits specified on the right side of the operator. Same
applies to the right side operator.
num1 >> 2 is right shift operator that moves the bits to the right, discards the far right bit,
and assigns the leftmost bit a value of 0. In our case output is 2 which is equivalent to
00000010
Output:
num1 & num2: 2
num1 | num2: 31
num1 ^ num2: 29
~num1: -12
num1 << 2: 44 num1 >> 2: 2
7) Ternary Operator
This operator evaluates a boolean expression and assign the value based on the result.
Syntax:
variable num1 = (expression) ? value if true : value if false
If the expression results true then the first value before the colon (:) is assigned to the variable
num1 else the second value is assigned to the num1.
Output:
num2: 200
num2: 100
Miscellaneous Operators
There are few other operators in C++ such as Comma operator and size of operator. We
will cover them in detail in a separate tutorial.
Operator Precedence in C++
This determines which operator needs to be evaluated first if an expression has more than one
operator. Operator with higher precedence at the top and lower precedence at the bottom.
Unary Operators
++ – – ! ~
Multiplicative
*/%
Additive
+–
Shift
<< >> >>>
Relational
> >= < <=
Equality
== !=
Bitwise AND
&
Bitwise XOR
^
Bitwise OR
|
Logical AND
&&
Logical OR
||
Ternary
?:
Assignment
= += -= *= /= %= > >= < <= &= ^= |=
If statement in C++
If statement consists a condition, followed by statement or a set of statements as shown in
syntax below:
if(condition){
Statement(s);
}
The statements inside if parenthesis (usually referred as if body) gets executed only when the
given condition is true. If the condition is false then the statements inside if body are
completely ignored.
Example of if statement
#include <iostream>
using namespace std;
int main(){
int num=70;
if( num < 100 ){
/* This cout statement will only execute,
* if the above condition is true
*/
cout<<"number is less than 100";
}
Output:
number is less than 100
if(condition_2) {
Statement2(s);
}
}
Statement1 would execute if the condition_1 is true. Statement2 would only execute if both
the conditions ( condition_1 and condition_2) are true.
Output:
number is less than 100
number is greater than 50
The statements inside ―if‖ would execute if the condition is true, and the statements inside
―else‖ would execute if the condition is false.
Flow diagram of if-else
Output:
num is greater than or equal 50
Note: The most important point to note here is that in if-else-if, as soon as the condition is
met, the corresponding set of statements get executed, rest gets ignored. If none of the
condition is met then the statements inside ―else‖ gets executed.
Example of if-else-if
#include <iostream>
using namespace std;
int main(){
int num;
cout<<"Enter an integer number between 1 & 99999: ";
cin>>num;
if(num <100 && num>=1) {
cout<<"Its a two digit number";
}
else if(num <1000 && num>=100) {
cout<<"Its a three digit number";
}
else if(num <10000 && num>=1000) {
cout<<"Its a four digit number";
}
else if(num <100000 && num>=10000) {
cout<<"Its a five digit number";
}
else {
cout<<"number is not between 1 & 99999";
}
return 0;
}
Output:
Enter an integer number between 1 & 99999: 8976
It‘s a four digit number
Switch Case statement in C++ with example
Switch case statement is used when we have multiple conditions and we need to perform
different action based on the condition. When we have multiple conditions and we need to
execute a block of statements when a particular condition is satisfied. In such case either we
can use lengthy if..else-if statement or switch case. The problem with lengthy if..else-if is that
it becomes complex when we have several conditions. The switch case is a clean and efficient
method of handling such scenarios.
The syntax of Switch case statement:
switch (variable or an integer expression)
{
case constant:
//C++ code
;
case constant:
//C++ code
;
default:
//C++ code
;
}
Switch Case statement is mostly used with break statement even though the break statement
is optional. We will first see an example without break statement and then we will discuss
switch case with break
Output:
Default: Value is: 5
Explanation: In switch I gave an expression, you can give variable as well. I gave the
expression num+2, where num value is 5 and after addition the expression resulted 7. Since
there is no case defined with value 4 the default case got executed.
Switch Case Flow Diagram
It evaluates the value of expression or variable (based on whatever is given inside switch
braces), then based on the outcome it executes the corresponding case.
Output:
Case2
Case3
Case4
Default
In the above program, we have the variable i inside switch braces, which means whatever the
value of variable i is, the corresponding case block gets executed. We have passed integer
value 2 to the switch, so the control switched to the case 2, however we don‘t have break
statement after the case 2 that caused the flow to continue to the subsequent cases till the end.
However this is not what we wanted, we wanted to execute the right case block and ignore
rest blocks. The solution to this issue is to use the break statement in after every case block.
Break statements are used when you want your program-flow to come out of the switch body.
Whenever a break statement is encountered in the switch body, the execution flow would
directly come out of the switch, ignoring rest of the cases. This is why you must end each
case block with the break statement.
Let‘s take the same example but this time with break statement.
#include <iostream>
using namespace std;
int main(){
int i=2;
switch(i) {
case 1:
cout<<"Case1 "<<endl;
break;
case 2:
cout<<"Case2 "<<endl;
break;
case 3:
cout<<"Case3 "<<endl;
break;
case 4:
cout<<"Case4 "<<endl;
break;
default:
cout<<"Default "<<endl;
}
return 0;
}
Output:
Case2
Now you can see that only case 2 got executed, rest of the subsequent cases were ignored.
Important Notes
1) Case doesn‘t always need to have order 1, 2, 3 and so on. It can have any integer value
after case keyword. Also, case doesn‘t need to be in an ascending order always, you can
specify them in any order based on the requirement.
2) You can also use characters in switch case. for example –
#include <iostream>
using namespace std;
int main(){
char ch='b';
switch(ch) {
case 'd': cout<<"Case1 ";
break;
case 'b': cout<<"Case2 ";
break;
case 'x': cout<<"Case3 ";
break;
case 'y': cout<<"Case4 ";
break;
default: cout<<"Default ";
}
return 0;
}
3) Nesting of switch statements are allowed, which means you can have switch statements
inside another switch. However nested switch statements should be avoided as it makes
program more complex and less readable
.
For loop in C++ with example
A loop is used for executing a block of statements repeatedly until a particular condition is
satisfied. For example, when you are displaying number from 1 to 100 you may want set the
value of a variable to 1 and display it 100 times, increasing its value by 1 on each loop
iteration.
Output:
Value of variable i is: 1
Value of variable i is: 2
Value of variable i is: 3
Value of variable i is: 4
Value of variable i is: 5
Value of variable i is: 6
For example:
#include <iostream>
using namespace std;
int main(){
for(int i=1; i>=1; i++){
cout<<"Value of variable i is: "<<i<<endl;
}
return 0;
}
This is an infinite loop as we are incrementing the value of i so it would always satisfy the
condition i>=1, the condition would never return false.
Here is another example of infinite for loop:
// infinite loop
for ( ; ; ) {
// statement(s)
}
Output:
21
9
56
99
202
While loop in C++ with example
In the last tutorial we discussed for loop. In this tutorial we will discuss while loop. As
discussed earlier, loops are used for executing a block of program statements repeatedly until
the given loop condition returns false.
Output:
Value of variable i is: 1
Value of variable i is: 2
Value of variable i is: 3
Value of variable i is: 4
Value of variable i is: 5
Value of variable i is: 6
#include <iostream>
using namespace std;
int main(){
int arr[]={21,87,15,99, -12};
/* The array index starts with 0, the
* first element of array has 0 index
* and represented as arr[0]
*/
int i=0;
while(i<5){
cout<<arr[i]<<endl;
i++;
}
}
Output:
21
87
15
99
-12
Output:
Value of num: 1
Value of num: 2
Value of num: 3
Value of num: 4
Value of num: 5
Value of num: 6
Here we have an integer array which has four elements. We are displaying the elements of it
using do-while loop.
#include <iostream>
using namespace std;
int main(){
int arr[]={21,99,15,109};
/* Array index starts with 0, which
* means the first element of array
* is at index 0, arr[0]
*/
int i=0;
do{
cout<<arr[i]<<endl;
i++;
}while(i<4);
return 0;
}
Output:
21
99
15
109
if (num==3) {
continue;
}
cout<<num<<" ";
}
return 0;
}
Output:
012456
Flow Diagram of Continue Statement
#include <iostream>
using namespace std;
int main(){
int j=4;
do {
if (j==7) {
j++;
continue;
}
cout<<"j is: "<<j<<endl;
j++;
}while(j<10);
return 0;
}
Output:
j is: 4
j is: 5
j is: 6
j is: 8
j is: 9
Output:
Value of num is: 10
Value of num is: 11
Value of num is: 12
Hey, I'm out of the loop
#include <iostream>
using namespace std;
int main(){
int var;
for (var =200; var>=10; var --) {
cout<<"var: "<<var<<endl;
if (var==197) {
break;
}
}
cout<<"Hey, I'm out of the loop";
return 0;
}
Output:
var: 200
var: 199
var: 198
var: 197
Hey, I'm out of the loop
#include <iostream>
using namespace std;
int main(){
int num=2;
switch (num) {
case 1: cout<<"Case 1 "<<endl;
break;
case 2: cout<<"Case 2 "<<endl;
break;
case 3: cout<<"Case 3 "<<endl;
break;
default: cout<<"Default "<<endl;
}
cout<<"Hey, I'm out of the switch case";
return 0;
}
Output:
Case 2
Hey, I'm out of the switch case
In this example, we have break statement after each Case block, this is because if we don‘t
have it then the subsequent case block would also execute. The output of the same program
without break would be:
Case 2
Case 3
Default
Hey, I'm out of the switch case
Program structure:
label1:
...
...
goto label2;
...
..
label2:
...
In a program we have any number of goto and label statements, the goto statement is
followed by a label name, whenever goto statement is encountered, the control of the
program jumps to the label specified in the goto statement.
goto statements are almost never used in any development as they are complex and makes
your program much less readable and more error prone. In place of goto, you can
use continue and break statement.
print:
cout<<"Even Number";
return 0;
}
Output:
Enter a number: 42
Even Number
Functions in C++ with example
A function is block of code which is used to perform a particular task, for example let‘s say
you are writing a large C++ program and in that program you want to do a particular task
several number of times, like displaying value from 1 to 10, in order to do that you have to
write few lines of code and you need to repeat these lines every time you display values.
Another way of doing this is that you write these lines inside a function and call that function
every time you want to display values. This would make you code simple, readable and
reusable.
Syntax of Function
return_type function_name (parameter_list)
{
//C++ Statements
}
int main(){
//Calling the function
cout<<sum(1,99);
return 0;
}
Output:
100
The same program can be written like this: Well, I am writing this program to let you
understand an important term regarding functions, which is function declaration. Let‘s see the
program first and then at the end of it we will discuss function declaration, definition and
calling of function.
#include <iostream>
using namespace std;
//Function declaration
int sum(int,int);
//Main function
int main(){
//Calling the function
cout<<sum(1,99);
return 0;
}
/* Function is defined after the main method
*/
int sum(int num1, int num2){
int num3 = num1+num2;
return num3;
}
Function Declaration: You have seen that I have written the same program in two ways, in
the first program I didn‘t have any function declaration and in the second program I have
function declaration at the beginning of the program. The thing is that when you define the
function before the main() function in your program then you don‘t need to do function
declaration but if you are writing your function after the main() function like we did in the
second program then you need to declare the function first, else you will get compilation
error.
function_name(parameters);
Now that we understood the working of function, lets see the types of function in C++
Types of function
We have two types of function in C++:
1) Built-in functions
2) User-defined functions
1) Built-in functions
Built-in functions are also known as library functions. We need not to declare and define
these functions as they are already written in the C++ libraries such as iostream, cmath etc.
We can directly call them when we need.
Output:
32
2) User-defined functions
We have already seen user-defined functions, the example we have given at the beginning of
this tutorial is an example of user-defined function. The functions that we declare and write in
our programs are user-defined functions. Let‘s see another example of user-defined functions.
User-defined functions
#include <iostream>
#include <cmath>
using namespace std;
//Declaring the function sum
int sum(int,int);
int main(){
int x, y;
cout<<"enter first number: ";
cin>> x;
Output:
enter first number: 22
enter second number: 19
Sum of these two :41
#include <iostream>
using namespace std;
int sum(int a, int b=10, int c=20);
int main(){
/* In this case a value is passed as
* 1 and b and c values are taken from
* default arguments.
*/
cout<<sum(1)<<endl;
Output:
Enter a number: 5
Factorial of entered number: 120
Base condition
In the above program, you can see that I have provided a base condition in the recursive
function. The condition is:
if (n <= 1)
return 1;
The purpose of recursion is to divide the problem into smaller problems till the base
condition is reached. For example in the above factorial program I am solving the factorial
function f(n) by calling a smaller factorial function f(n-1), this happens repeatedly until the n
value reaches base condition(f(1)=1). If you do not define the base condition in the recursive
function then you will get stack overflow error.
#include <iostream>
using namespace std;
int fa(int);
int fb(int);
int fa(int n){
if(n<=1)
return 1;
else
return n*fb(n-1);
}
int fb(int n){
if(n<=1)
return 1;
else
return n*fa(n-1);
}
int main(){
int num=5;
cout<<fa(num);
return 0;
}
Output:
120
Arrays in C++
An array is a collection of similar items stored in contiguous memory locations. In
programming, sometimes a simple variable is not enough to hold all the data. For example,
let‘s say we want to store the marks of 500 students, having 500 different variables for this
task is not feasible, we can define an array with size 500 that can hold the marks of all
students.
Method 2:
int arr[] = {10, 20, 30, 40, 50};
Method 3:
int arr[5] = {10, 20, 30, 40, 50};
Accessing Array Elements
Array index starts with 0, which means the first array element is at index 0, second is at index
1 and so on. We can use this information to display the array elements. See the code below:
#include <iostream>
using namespace std;
int main(){
int arr[] = {11, 22, 33, 44, 55};
cout<<arr[0]<<endl;
cout<<arr[1]<<endl;
cout<<arr[2]<<endl;
cout<<arr[3]<<endl;
cout<<arr[4]<<endl;
return 0;
}
Output:
11
22
33
44
55
Although this code worked fine, displaying all the elements of array like this is not
recommended. When you want to access a particular array element then this is fine but if you
want to display all the elements then you should use a loop like this:
#include <iostream>
using namespace std;
int main(){
int arr[] = {11, 22, 33, 44, 55};
int n=0;
while(n<=4){
cout<<arr[n]<<endl;
n++;
}
return 0;
}
Multidimensional Arrays in C++
Multidimensional arrays are also known as array of arrays. The data in multidimensional
array is stored in a tabular form as shown in the diagram below:
Initialization:
We can initialize the array in many ways:
Method 1:
int arr[2][3] = {10, 11 ,12 ,20 ,21 , 22};
Method 2:
This way of initializing is preferred as you can visualize the rows and columns here.
int arr[2][3] = {{10, 11 ,12} , {20 ,21 , 22}};
int main(){
int arr[2][3] = {{11, 22, 33}, {44, 55, 66}};
for(int i=0; i<2;i++){
for(int j=0; j<3; j++){
cout<<"arr["<<i<<"]["<<j<<"]: "<<arr[i][j]<<endl;
}
}
return 0;
}
Output:
arr[0][0]: 11
arr[0][1]: 22
arr[0][2]: 33
arr[1][0]: 44
arr[1][1]: 55
arr[1][2]: 66
Initialization:
We can initialize the array in many ways:
Method 1:
int arr[2][3][2] = {1, -1 ,2 ,-2 , 3 , -3, 4, -4, 5, -5, 6, -6};
Method 2:
This way of initializing is preferred as you can visualize the rows and columns here.
int arr[2][3][2] = {
{ {1,-1}, {2, -2}, {3, -3}},
{ {4, -4}, {5, -5}, {6, -6}}
}
int main(){
// initializing the array
int arr[2][3][2] = {
{ {1,-1}, {2,-2}, {3,-3} },
{ {4,-4}, {5,-5}, {6,-6} }
};
// displaying array values
for (int x = 0; x < 2; x++) {
for (int y = 0; y < 3; y++) {
for (int z = 0; z < 2; z++) {
cout<<arr[x][y][z]<<" ";
}
}
}
return 0;
}
Output:
1 -1 2 -2 3 -3 4 -4 5 -5 6 -6
Strings in C++
Strings are words that are made up of characters, hence they are known as sequence of
characters. In C++ we have two ways to create and use strings:
1) By creating char arrays and treat them as string
2) By creating string object
Let‘s discuss these two ways of creating string first and then we will see which method is
better and why.
Output:
A Song of Ice and Fire
#include <iostream>
using namespace std;
int main(){
char book[50];
cout<<"Enter your favorite book name:";
//reading user input
cin>>book;
cout<<"You entered: "<<book;
return 0;
}
Output:
Enter your favorite book name:The Murder of Roger Ackroyd
You entered: The
You can see that only the ―The‖ got captured in the book and remaining part after space got
ignored. How to deal with this then? Well, for this we can use cin.get function, which reads
the complete line entered by user.
Output:
Enter a String:XYZ
You entered: XYZ
The string after push_back: XYZA
The string after pop_back: XYZ
The advantage of using this method is that you need not to declare the size of the string, the
size is determined at run time, so this is better memory management method. The memory is
allocated dynamically at runtime so no memory is wasted.
Pointers in C++
Pointer is a variable in C++ that holds the address of another variable. They have data
type just like variables, for example an integer type pointer can hold the address of an integer
variable and character type pointer can hold the address of char variable.
Syntax of pointer
data_type *pointer_name;
Assignment
As I mentioned above, an integer type pointer can hold the address of another int variable.
Here we have an integer variable var and pointer p holds the address of var. To assign the
address of variable to pointer we use ampersand symbol (&).
/* This is how you assign the address of another variable
* to the pointer
*/
p = &var;
Example of Pointer
Let‘s take a simple example to understand what we discussed above.
#include <iostream>
using namespace std;
int main(){
//Pointer declaration
int *p, var=101;
//Assignment
p = &var;
Output:
Address of var: 0x7fff5dfffc0c
Address of var: 0x7fff5dfffc0c
Address of p: 0x7fff5dfffc10
Value of var: 101
Incorrect:
p = &arr;
Output:
1
2
3
4
5
6
/* All the following three cases are same they increment the value
* of variable that the pointer p points.
*/
++*p;
++(*p);
++*(p);
Output:
100
A
Output:
101
A
public:
//Functions
void brake(){
}
void slowDown(){
}
};
int main()
{
//ford is an object
Car ford;
}
Abstraction
Abstraction is a process of hiding irrelevant details from user. For example, When you send
an sms you just type the message, select the contact and click send, the phone shows you that
the message has been sent, what actually happens in background when you click send is
hidden from you as it is not relevant to you.
Encapsulation
Encapsulation is a process of combining data and function into a single unit like capsule. This
is to avoid the access of private data members from outside the class. To achieve
encapsulation, we make all data members of class private and create public functions; using
them we can get the values from these data members or set the value to these data members.
Inheritance
Inheritance is a feature using which an object of child class acquires the properties of parent
class.
#include <iostream>
using namespace std;
class ParentClass {
//data member
public:
int var1 =100;
};
class ChildClass: public ParentClass {
public:
int var2 = 500;
};
int main(void) {
ChildClass obj;
}
Now this object obj can use the properties (such as variable var1) of ParentClass.
Polymorphism
Function overloading and Operator overloading are examples of polymorphism.
Polymorphism is a feature using which an object behaves differently in different situation.
In function overloading we can have more than one function with same name but different
numbers, type or sequence of arguments.
Polymorphism Example
#include <iostream>
using namespace std;
class Sum {
public:
int add(int num1,int num2){
return num1 + num2;
}
int add(int num1, int num2, int num3){
return num1 + num2 + num3;
}
};
int main(void) {
//Object of class Sum
Sum obj;
Output:
60
33
Constructors in C++
Constructor is a special member function of a class that initializes the object of the class.
Constructor name is same as class name and it doesn‘t have a return type. Let‘s take a simple
example to understand the working of constructor.
#include <iostream>
using namespace std;
class constructorDemo{
public:
int num;
char ch;
/* This is a default constructor of the
* class, do note that it's name is same as
* class name and it doesn't have return type.
*/
constructorDemo() {
num = 100; ch = 'A';
}
};
int main(){
/* This is how we create the object of class,
* I have given the object name as obj, you can
* give any name, just remember the syntax:
* class_name object_name;
*/
constructorDemo obj;
/* This is how we access data members using object
* we are just checking that the value we have
* initialized in constructor are reflecting or not.
*/
cout<<"num: "<<obj.num<<endl;
cout<<"ch: "<<obj.ch;
return 0;
}
Output:
num: 100
ch: A
1) Default Constructor
A default constructor doesn‘t have any arguments (or parameters)
#include <iostream>
using namespace std;
class Website{
public:
//Default constructor
Website() {
cout<<"Welcome to BeginnersBook"<<endl;
}
};
int main(void){
/*creating two objects of class Website.
* This means that the default constructor
* should have been invoked twice.
*/
Website obj1;
Website obj2;
return 0;
}
Output:
Welcome to BeginnersBook
Welcome to BeginnersBook
When you don‘t specify any constructor in the class, a default constructor with no code
(empty body) would be inserted into your code by compiler.
2) Parameterized Constructor
Constructors with parameters are known as Parameterized constructors. These type of
constructor allows us to pass arguments while object creation. Let‘s see how they look:
Let‘s say class name is XYZ
Default constructor:
XYZ() {
}
....
XYZ obj;
....
Parameterized Constructor:
XYZ(int a, int b) {
}
...
XYZ obj(10, 20);
Example:
#include <iostream>
using namespace std;
class Add{
public:
//Parameterized constructor
Add(int num1, int num2) {
cout<<(num1+num2)<<endl;
}
};
int main(void){
/* One way of creating object. Also
* known as implicit call to the
* constructor
*/
Add obj1(10, 20);
/* Another way of creating object. This
* is known as explicit calling the
* constructor.
*/
Add obj2 = Add(50, 60);
return 0;
}
Output:
30
110
Destructors in C++
A destructor is a special member function that works just opposite to constructor,
unlike constructors that are used for initializing an object, destructors destroy (or delete) the
object.
Syntax of Destructor
~class_name()
{
//Some code
}
Similar to constructor, the destructor name should exactly match with the class name. A
destructor declaration should always begin with the tilde(~) symbol as shown in the syntax
above.
Destructor Example
#include <iostream>
using namespace std;
class HelloWorld{
public:
//Constructor
HelloWorld(){
cout<<"Constructor is called"<<endl;
}
//Destructor
~HelloWorld(){
cout<<"Destructor is called"<<endl;
}
//Member function
void display(){
cout<<"Hello World!"<<endl;
}
};
int main(){
//Object created
HelloWorld obj;
//Member function called
obj.display();
return 0;
}
Output:
Constructor is called
Hello World!
Destructor is called
Destructor rules
1) Name should begin with tilde sign(~) and must match class name.
2) There cannot be more than one destructor in a class.
3) Unlike constructors that can have parameters, destructors do not allow any parameter.
4) They do not have any return type, just like constructors.
5) When you do not specify any destructor in a class, compiler generates a default destructor
and inserts it into your code.
Structures in C++
Structure is a compound data type that contains different variables of different types. For
example, you want to store Student details like student name, student roll num, student age.
You have two ways to do it, one way is to create different variables for each data, but the
downfall of this approach is that if you want to store the details of multiple students, and in
that case it is not feasible to create separate set of variables for each student.
The second and best way of doing it by creating a structure like this:
struct Student
{
char stuName[30];
int stuRollNo;
int stuAge;
};
Now these three members combined will act like a separate variable and you can create
structure variable like this:
structure_name variable_name
So if you want to hold the information of two students using this structure then you can do it
like this:
Student s1, s2;
Then I can access the members of Student structure like this:
//Assigning name to first student
s1.stuName = "Ajeet";
//Assigning age to the second student
s2.stuAddr = 22;
Similarly I can set and get the values of other data members of the structure for every student.
Let‘s see a complete example to put this up all together:
Output:
Enter Student Name: Negan
ENter Student Roll No: 4101003
Enter Student Age: 22
Student Record:
Name: Negan
Roll No: 4101003
Age: 22
Output:
Enter Student Name: Rick
Enter Student Roll No: 666123
Enter Student Age: 19
Student Record:
Name: Rick
Roll No: 666123
Age: 19
Output:
Enter Student Name: Tyrion lannister
Enter Student Roll No: 333901
Enter Student Age: 39
Student Record:
Name: Tyrion lannister
Roll No: 333901
Age: 39
Enumeration in C++
Enum is a user defined data type where we specify a set of values for a variable and the
variable can only take one out of a small set of possible values. We use enum keyword to
define an Enumeration.
enum direction {East, West, North, South}dir;
Here Enumeration name is direction which can only take one of the four specified values, the
dir at the end of the declaration is an enum variable.
Let‘s take a simple example to understand this:
Here I have assigned the value West to the enum variable dir and when I displayed the value
of dir it shows 1. This is because by default the values are in increasing order starting from 0,
which means East is 0, West is 1, North is 2 and South is 3.
Output:
3
Output:
44
Inheritance in C++
Inheritance is one of the feature of Object Oriented Programming System(OOPs), it allows
the child class to acquire the properties (the data members) and functionality (the member
functions) of parent class.
What is child class?
A class that inherits another class is known as child class, it is also known as derived class or
subclass.
What is parent class?
The class that is being inherited by other class is known as parent class, super class or base
class.
Syntax of Inheritance
class parent_class
{
//Body of parent class
};
class child_class : access_modifier parent_class
{
//Body of child class
};
#include <iostream>
using namespace std;
class Teacher {
public:
Teacher(){
cout<<"Hey Guys, I am a teacher"<<endl;
}
string collegeName = "Beginnersbook";
};
//This class inherits Teacher class
class MathTeacher: public Teacher {
public:
MathTeacher(){
cout<<"I am a Math Teacher"<<endl;
}
string mainSub = "Math";
string name = "Negan";
};
int main() {
MathTeacher obj;
cout<<"Name: "<<obj.name<<endl;
cout<<"College Name: "<<obj.collegeName<<endl;
cout<<"Main Subject: "<<obj.mainSub<<endl;
return 0;
}
Output:
Hey Guys, I am a teacher
I am a Math Teacher
Name: Negan
College Name: Beginnersbook
Main Subject: Math
Single inheritance
In Single inheritance one class inherits one class exactly.
For example: Let‘s say we have class A and B
B inherits A
Output:
Constructor of A class
Constructor of B class
2)Multilevel Inheritance
In this type of inheritance one class inherits another child class.
C inherits B and B inherits A
Output:
Constructor of A class
Constructor of B class
Constructor of C class
Multiple Inheritance
In multiple inheritance, a class can inherit more than one class. This means that in this type of
inheritance a single child class can have multiple parent classes.
For example:
C inherits A and B both
4)Hierarchical Inheritance
In this type of inheritance, one parent class has more than one child class. For example:
Class B and C inherits class A
Output:
Constructor of A class
Constructor of C class
5) Hybrid Inheritance
Hybrid inheritance is a combination of more than one type of inheritance. For example, A
child and parent class relationship that follows multiple and hierarchical inheritance both can
be called hybrid inheritance.
Polymorphism in C++
Polymorphism is a feature of OOPs that allows the object to behave differently in different
conditions. In C++ we have two types of polymorphism:
1) Compile time Polymorphism – This is also known as static (or early) binding.
2) Runtime Polymorphism – This is also known as dynamic (or late) binding.
Output:
Output: 30
Output: 66
2) Runtime Polymorphism
Function overriding is an example of Runtime polymorphism.
Function Overriding: When child class declares a method, which is already present in the
parent class then this is called function overriding, here child class overrides the parent class.
In case of function overriding we have two definitions of the same function; one is parent
class and one in child class. The call to the function is determined at runtime to decide which
definition of the function is to be called, thats the reason it is called runtime polymorphism.
Example of Runtime Polymorphism
#include <iostream>
using namespace std;
class A {
public:
void disp(){
cout<<"Super Class Function"<<endl;
}
};
class B: public A{
public:
void disp(){
cout<<"Sub Class Function";
}
};
int main() {
//Parent class object
A obj;
obj.disp();
//Child class object
B obj2;
obj2.disp();
return 0;
}
Output:
Super Class Function
Sub Class Function
The easiest way to remember this rule is that the parameters should qualify any one or more
of the following conditions, they should have different type, number or sequence of
parameters.
For example:
These two functions have different parameter type:
sum(int num1, int num2)
sum(double num1, double num2)
All of the above three cases are valid case of overloading. We can have any number of
functions, just remember that the parameter list should be different. For example:
int sum(int, int)
double sum(int, int)
This is not allowed as the parameter list is same. Even though they have different return
types, it‘s not valid.
#include <iostream>
using namespace std;
class Addition {
public:
int sum(int num1,int num2) {
return num1+num2;
}
int sum(int num1,int num2, int num3) {
return num1+num2+num3;
}
};
int main(void) {
Addition obj;
cout<<obj.sum(20, 15)<<endl;
cout<<obj.sum(81, 100, 10);
return 0;
}
Output:
35
191
Output:
100
5006.52
#include <iostream>
using namespace std;
class BaseClass {
public:
void disp(){
cout<<"Function of Parent Class";
}
};
class DerivedClass: public BaseClass{
public:
void disp() {
cout<<"Function of Child Class";
}
};
int main() {
DerivedClass obj = DerivedClass();
obj.disp();
return 0;
}
Output:
Function of Child Class
Note: In function overriding, the function in parent class is called the overridden function and
function in child class is called overriding function.
#include <iostream>
using namespace std;
class BaseClass {
public:
void disp(){
cout<<"Function of Parent Class";
}
};
class DerivedClass: public BaseClass{
public:
void disp() {
cout<<"Function of Child Class";
}
};
int main() {
/* Reference of base class pointing to
* the object of child class.
*/
BaseClass obj = DerivedClass();
obj.disp();
return 0;
}
Output:
Function of Parent Class
If you want to call the Overridden function from overriding function then you can do it like
this:
parent_class_name::function_name
To do this in the above example, we can write following statement in the disp() function of
child class:
BaseClass::disp();
#include <iostream>
using namespace std;
// overloaded functions
float sum(int, int);
float sum(float, float);
float sum(int, float);
float sum(float, int);
int main(){
//This will call the second function
cout<<sum(15.7f, 12.7f)<<endl;
return 0;
}
float sum(int a, int b){
return a+b;
}
float sum(float a, float b){
return a+b;
}
float sum(int a, float b){
return a+b;
}
float sum(float a, int b){
return a+b;
}
Output:
28.4
300
120.7
120.8
Function Overriding
Function overriding is a feature of OOPs Programming that allows us to override a function
of parent class in child class.
Example:
#include<iostream>
using namespace std;
//Parent class or super class or base class
class A{
public:
void disp() {
cout<<"Parent Class disp() function"<<endl;
}
void xyz() {
cout<<"xyz() function of parent class";
}
};
//child class or sub class or derived class
class B : public A{
public:
/* Overriding disp() function of parent class
* and giving a different definition to it.
*/
void disp() {
cout<<"Child class disp() function"<<endl;
}
};
int main(){
//Creating object of child class B
B obj;
obj.disp();
/* If you want to call the overridden function
* (the same function which is present in parent class)
* from the child class then assign the reference of
* parent class to the child class object.
*/
A obj2 = B();
obj2.disp();
}
Output:
Child class disp() function
Parent Class disp() function
#include<iostream>
using namespace std;
//Parent class or super class or base class
class Animal{
public:
void animalSound(){
cout<<"This is a generic Function";
}
};
//child class or sub class or derived class
class Dog : public Animal{
public:
void animalSound(){
cout<<"Woof";
}
};
int main(){
Animal *obj;
obj = new Dog();
obj->animalSound();
return 0;
}
Output:
This is a generic Function
Output:
Woof
Encapsulation in C++ with example
Encapsulation is a process of combining data members and functions in a single unit called
class. This is to prevent the access to the data directly, the access to them is provided through
the functions of the class. It is one of the popular features of Object Oriented Programming
(OOPs) that helps in data hiding.
How Encapsulation is achieved in a class
To do this:
1) Make the entire data members private.
2) Create public setter and getter functions for each data member in such a way that the set
function set the value of data member and get function get the value of data member.
Let‘s see this in an example Program:
Encapsulation Example in C++
Here we have two data members num and ch, we have declared them as private so that they
are not accessible outside the class, this way we are hiding the data. The only way to get and
set the values of these data members is through the public getter and setter functions.
#include<iostream>
using namespace std;
class ExampleEncap{
private:
/* Since we have marked these data members private,
* any entity outside this class cannot access these
* data members directly, they have to use getter and
* setter functions.
*/
int num;
char ch;
public:
/* Getter functions to get the value of data members.
* Since these functions are public, they can be accessed
* outside the class, thus provide the access to data members
* through them
*/
int getNum() const {
return num;
}
char getCh() const {
return ch;
}
/* Setter functions, they are called for assigning the values
* to the private data members.
*/
void setNum(int num) {
this->num = num;
}
void setCh(char ch) {
this->ch = ch;
}
};
int main(){
ExampleEncap obj;
obj.setNum(100);
obj.setCh('A');
cout<<obj.getNum()<<endl;
cout<<obj.getCh()<<endl;
return 0;
}
Output:
100
A
public:
void setMyValues(int n, char c) {
num = n; ch = c;
}
void getMyValues() {
cout<<"Numbers is: "<<num<< endl;
cout<<"Char is: "<<ch<<endl;
}
};
int main(){
AbstractionExample obj;
obj.setMyValues(100, 'X');
obj.getMyValues();
return 0;
}
Output:
Numbers is: 100
Char is: X
Advantage of data abstraction
The major advantage of using this feature is that when the code evolves and you need to
make some adjustments in the code then you only need to modify the high level class where
you have declared the members as private. Since none class is accessing these data members
directly, you do not need to change the low level (user level) class code.
Imagine if you had made these data members public, if at some point you want to change the
code, you would have to make the necessary adjustments to all the classes that are accessing
the members directly.
Other advantages of data abstraction are:
1) Makes the application secure by making data private and avoiding the user level error that
may corrupt the data.
2) This avoids code duplication and increases the code reusability.
Interfaces in C++: Abstract Class
In C++, we use terms abstract class and interface interchangeably. A class with pure virtual
function is known as abstract class. For example the following function is a pure virtual
function:
virtual void fun() = 0;
A pure virtual function is marked with a virtual keyword and has = 0 after its signature. You
can call this function an abstract function as it has no body. The derived class must give the
implementation to all the pure virtual functions of parent class else it will become abstract
class by default.
Why we need an abstract class?
Let‘s understand this with the help of a real life example. Let‘s say we have a class Animal,
animal sleeps, animal make sound, etc. For now I am considering only these two behaviours
and creating a class Animal with two functions sound() and sleeping().
Now, we know that animal sounds are different cat says ―meow‖, dog says ―woof‖. So what
implementation do I give in Animal class for the function sound(), the only and correct way
of doing this would be making this function pure abstract so that I need not give
implementation in Animal class but all the classes that inherits Animal class must give
implementation to this function. This way I am ensuring that all the Animals have sound but
they have their unique sound.
The same example can be written in a C++ program like this:
Abstract class Example
#include<iostream>
using namespace std;
class Animal{
public:
//Pure Virtual Function
virtual void sound() = 0;
Friend Class:
A friend class is a class that can access the private and protected members of a class in which
it is declared as friend. This is needed when we want to allow a particular class to access the
private and protected members of a class.
Output:
A
11
Friend Function:
Similar to friend class, this function can access the private and protected members of another
class. A global function can also be declared as friend as shown in the example below:
Friend Function Example
#include <iostream>
using namespace std;
class XYZ {
private:
int num=100;
char ch='Z';
public:
friend void disp(XYZ obj);
};
//Global Function
void disp(XYZ obj){
cout<<obj.num<<endl;
cout<<obj.ch<<endl;
}
int main() {
XYZ obj;
disp(obj);
return 0;
}
Output:
100
Z