Oop Notees
Oop Notees
Oop Notees
C++ language is a direct descendant of C programming language with additional features such as
type checking, object oriented programming, exception handling etc.
2) Object oriented – C++ supports object oriented programming features, which means we can
use the popular OOPs concepts such as Abstraction, Inheritance, Encapsulation and Inheritance
in C++ programs, these features make writing code in C++ a lot easier. We will cover them in
detail in this tutorial series.
3) Portable – Most of C++ compilers supports ANSI standards that makes C++ portable because
the code you write on one operating system can be run on other Operating system without
making any change. We cannot say C++ a fully platform independent language as certain things
in C++ are not portable, such as drawing graphics on a screen, since standard C++ has no
graphics or GUI API.
5) Exception handling: Just like Java we can do exception handling in C++ which makes it
easier to identify and handle the exceptions.
6) Simple – Last but not least, just like C, it is easier to write a program in C++. Once you get
familiar with the syntax of C++ programming language, it becomes a lot easier to code in C++.
Example 1:
Write a program that prints hello world. Include comments within the code
Solution
/*
* Multiple line
* comment
*/
#include<iostream>
return 0;
}
Output:
Hello World!
Discussion
1. Comments – You can see two types of comments in the above program
Comments as the names suggests are just a text written by programmer during code
development. Comment doesn’t affect your program logic in any way, you can write whatever
you want in comments but it should be related to the code and have some meaning so that when
someone else look into your code, the person should understand what you did in the code by just
reading your comment.
For example:
Now if someone reads my comment he or she can understand what I did there just by reading my
comment. This improves readability of your code and when you are working on a project with
your team mates, this becomes essential aspect.
2. #include<iostream> – This statements tells the compiler to include iostream file. This file
contains pre defined input/output functions that we can use in our program.
3. using namespace std; – A namespace is like a region, where we have functions, variables etc
and their scope is limited to that particular region. Here std is a namespace name, this tells the
4. int main() – As the name suggests this is the main function of our program and the execution
of program begins with this function, the int here is the return type which indicates to the
compiler that this function will return a integer value. That is the main reason we have a return 0
statement at the end of main function.
5. cout << “Hello World!”; – The cout object belongs to the iostream file and the purpose of this
object is to display the content between double quotes as it is on the screen. This object can also
display the value of variables on screen(don’t worry, we will see that in the coming tutorials).
6. return 0; – This statement returns value 0 from the main() function which indicates that the
execution of main function is successful. The value 1 represents failed execution.
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.
For example:
int num1,num2;
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++.
char: holds character value like ‘c’, ‘F’, ‘B’, ‘p’, ‘q’ etc.
Before going further lets discuss what is scope first. When we discussed the Hello World
Program, we have seen the curly braces in the program like this:
int main {
//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. Lets move on to the types of variables based on the
scope.
1. Global variable
2. 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.
Here we have a global variable myVar, that is declared outside of main. We have accessed the
variable twice in the main() function without any issues.
#include <iostream>
using namespace std;
// This is a global variable
char myVar = 'A';
int main()
{
cout <<"Value of myVar: "<< myVar<<endl;
myVar='Z';
cout <<"Value of myVar: "<< myVar;
return 0;
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.
Lets see an example having same name global and local variable.
#include <iostream>
using namespace std;
// This is a global variable
char myVar = 'A';
char myFuncn() {
// This is a local variable
char myVar = 'B';
return myVar;
}
int main()
{
cout <<"Funcn call: "<< myFuncn()<<endl;
cout <<"Value of myVar: "<< myVar<<endl;
myVar='Z';
cout <<"Funcn call: "<< myFuncn()<<endl;
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().
Data types define the type of data a variable can hold, for example an integer variable can hold
integer data, a character type variable can hold character data etc.
Data types in C++ are categorised in three groups: Built-in, user-defined and Derived.
char ch = 'A';
bool b = true;
wchar_t: Wide Character. This should be avoided because its size is implementation defined and
not reliable.
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.
– is for subtraction.
* is for multiplication.
/ is for division.
% is for modulo.
Note: Modulo operator returns remainder, for example 20 % 5 would return 0
Output:
2) Assignment Operators
Assignments operators in C++ are: =, +=, -=, *=, /=, %=
Output:
Output:
4) Logical Operators
Logical Operators are used with binary variables. They are mainly used in conditional statements
and loops for evaluating a condition.
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 or equal to right side.
<= returns true if left side is less than or equal to right side.
Output:
6) Bitwise Operators
There are six bitwise Operators: &, |, ^, ~, <<, >>
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 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:
7) Ternary Operator
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 sizeof operator. We will
cover them in detail in a separate tutorial.
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
*/%
Shift
<< >> >>>
Relational
> >= < <=
Equality
== !=
Bitwise AND
&
Bitwise XOR
^
Bitwise OR
|
Logical AND
&&
Logical OR
||
Ternary
?:
Assignment
= += -= *= /= %= > >= < <= &= ^= |=
Sometimes we need to execute a block of statements only when a particular condition is met or
not met. This is called decision making, as we are executing a certain code after making a
decision in the program logic. For decision making in C++, we have four types of control
statements (or control structures), which are as follows:
a) if statement
b) nested if statement
c) if-else statement
d) if-else-if statement
If statement in C++
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:
When there is an if statement inside another if statement then it is called the nested if statement.
The structure of nested if looks like this:
if(condition_1) {
Statement1(s);
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:
if(condition) {
Statement(s);
}
else {
Statement(s);
}
The statements inside “if” would execute if the condition is true, and the statements inside “else”
would execute if the condition is false.
Output:
if-else-if statement is used when we need to check multiple conditions. In this control structure
we have only one “if” and one “else”, however we can have multiple “else if” blocks. This is
how it looks:
if(condition_1) {
/*if condition_1 is true execute this*/
statement(s);
}
else if(condition_2) {
/* execute this if condition_1 is not met and
* condition_2 is met
*/
statement(s);
}
else if(condition_3) {
/* execute this if condition_1 & condition_2 are
* not met and condition_3 is met
*/
statement(s);
}
.
.
.
else {
/* if none of the condition is true
* then these statements gets executed
*/
statement(s);
}
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;
Output:
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.
Output:
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.
Before we discuss about break statement, Let’s see what happens when we don’t use break
statement in switch case. See the example below:
#include <iostream>
using namespace std;
int main(){
int i=2;
switch(i) {
case 1: cout<<"Case1 "<<endl;
case 2: cout<<"Case2 "<<endl;
case 3: cout<<"Case3 "<<endl;
case 4: cout<<"Case4 "<<endl;
default: cout<<"Default "<<endl;
}
return 0;
}
Output:
Case2
Case3
Case4
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
#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.
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.
In C++ we have three types of basic loops: for, while and do-while. In this tutorial we will learn
how to use “for loop” in C++.
First step: In for loop, initialization happens first and only once, which means that the
initialization part of for loop only executes once.
Second step: Condition in for loop is evaluated on each loop iteration, if the condition is true
then the statements inside for for loop body gets executed. Once the condition returns false, the
statements in for loop does not execute and the control gets transferred to the next statement in
the program after for loop.
Third step: After every execution of for loop’s body, the increment/decrement part of for loop
executes that updates the loop counter.
Fourth step: After third step, the control jumps to second step and condition is re-evaluated.
The steps from second to fourth repeats until the loop condition returns false.
#include <iostream>
Output:
A loop is said to be infinite when it executes repeatedly and never stops. This usually happens by
mistake. When you set the condition in for loop in such a way that it never return false, it
becomes infinite loop.
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.
// infinite loop
for ( ; ; ) {
// statement(s)
}
Output:
21
9
56
99
202
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.
In while loop, condition is evaluated first and if it returns true then the statements inside while
loop execute, this happens repeatedly until the condition returns false. When condition returns
false, the control comes out of loop and jumps to the next statement in the program after while
loop.
Note: The important point to note when using while loop is that we need to use increment or
decrement statement inside while loop so that the loop variable gets changed on each iteration,
and at some point condition returns false. This way we can end the execution of while loop
otherwise the loop would execute indefinitely.
Output:
A while loop that never stops is said to be the infinite while loop, when we give the condition in
such a way so that it never returns false, then the loops becomes infinite and repeats itself
indefinitely.
An example of infinite while loop:
This loop would never end as I’m decrementing the value of i which is 1 so the condition i<=6
would never return false.
#include <iostream>
using namespace std;
int main(){
int i=1; while(i<=6) {
cout<<"Value of variable i is: "<<i<<endl; i--;
}
}
Output:
21
87
15
99
-12
As discussed in the last tutorial about while loop, a loop is used for repeating a block of
statements until the given loop condition returns false. In this tutorial we will see do-while loop.
do-while loop is similar to while loop, however there is a difference between them: In while
loop, condition is evaluated first and then the statements inside loop body gets executed, on the
First, the statements inside loop execute and then the condition gets evaluated, if the condition
returns true then the control jumps to the “do” for further repeated execution of it, this happens
repeatedly until the condition returns false. Once condition returns false control jumps to the next
statement in the program after do-while.
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
Continue statement is used inside loops. Whenever a continue statement is encountered inside a
loop, control directly jumps to the beginning of the loop for next iteration, skipping the execution
of statements inside loop’s body for the current iteration.
As you can see that the output is missing the value 3, however the for loop iterate though the
num value 0 to 6. This is because we have set a condition inside loop in such a way, that the
continue statement is encountered when the num value is equal to 3. So for this iteration the loop
skipped the cout statement and started the next iteration of loop.
#include <iostream>
using namespace std;
int main(){
for (int num=0; num<=6; num++) {
/* This means that when the value of
* num is equal to 3 this continue statement
* would be encountered, which would make the
* control to jump to the beginning of loop for
* next iteration, skipping the current iteration
*/
if (num==3) {
continue;
}
cout<<num<<" ";
}
return 0;
}
Output:
012456
Output:
Value of j: 6
Value of j: 5
Value of j: 3
Value of j: 2
Value of j: 1
Value of j: 0
Output:
j is: 4
j is: 5
j is: 6
j is: 8
j is: 9
a) Use break statement to come out of the loop instantly. Whenever a break statement is
encountered inside a loop, the control directly comes out of loop terminating it. It is used along
with if statement, whenever used inside loop(see the example below) so that it occurs only for a
particular condition.
b) It is used in switch case control structure after the case blocks. Generally all cases in switch
case are followed by a break statement to avoid the subsequent cases (see the example below)
execution. Whenever it is encountered in switch-case block, the control comes out of the switch-
case body.
In the example below, we have a while loop running from 10 to 200 but since we have a break
statement that gets encountered when the loop counter variable value reaches 12, the loop gets
terminated and the control jumps to the next statement in program after the loop body.
#include <iostream>
using namespace std;
int main(){
int num =10;
while(num<=200) {
cout<<"Value of num is: "<<num<<endl;
if (num==12) {
break;
}
num++;
}
cout<<"Hey, I'm out of the loop";
return 0;
}
Output:
Output:
var: 200
var: 199
var: 198
var: 197
Hey, I'm out of the loop
Output:
Case 2
Hey, I'm out of the switch case
Case 2
Case 3
Default
Hey, I'm out of the switch case
The goto statement is used for transferring the control of a program to a given label. The syntax
of goto statement looks like this:
goto label_name;
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:
Output:
Enter a number: 42
Even Number
Functions in C++
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
#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.
return_type function_name(parameter_list);
Note: While providing parameter_list you can avoid the parameter names, just like I did in the
above example. I have given int sum(int,int); instead of int sum(int num1,int num2);.
Function definition: Writing the full body of function is known as defining a function.
syntax of function definition:
return_type function_name(parameter_list) {
//Statements inside function
}
function_name(parameters);
Now that we understood the working of function, lets see the types of function in C++
1) Built-in functions
2) User-defined functions
1) Build-it 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.
Here we are using built-in function pow(x,y) which is x to the power y. This function is declared
in cmath header file so we have included the file in our program using #include directive.
#include <iostream>
#include <cmath>
using namespace std;
int main(){
/* Calling the built-in function
* pow(x, y) which is x to the power y
* We are directly calling this function
*/
cout<<pow(2,5);
return 0;
}
Output:
32
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. Lets 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:
The default arguments are used when you provide no arguments or only few arguments while
calling a function. The default arguments are used during compilation of program. For example,
lets say you have a user-defined function sum declared like this: int sum(int a=10, int b=20), now
while calling this function you do not provide any arguments, simply called sum(); then in this
case the result would be 30, compiler used the default values 10 and 20 declared in function
signature. If you pass only one argument like this: sum(80) then the result would be 100, using
the passed argument 80 as first value and 20 taken from the default argument.
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:
31
23
6
As you have seen in the above example that I have assigned the default values for only two
arguments b and c during function declaration. It is up to you to assign default values to all
arguments or only selected arguments but remember the following rule while assigning default
values to only some of the arguments:
If you assign default value to an argument, the subsequent arguments must have default
values assigned to them, else you will get compilation error.
The process in which a function calls itself is known as recursion and the corresponding function
is called the recursive function. The popular example to understand the recursion is factorial
function.
Factorial function: f(n) = n*f(n-1), base condition: if n<=1 then f(n) = 1. Don’t worry we wil
discuss what is base condition and why it is important.
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.
Direct recursion: When function calls itself, it is called direct recursion, the example we have
seen above is a direct recursion example.
Indirect recursion: When function calls another function and that function calls the calling
function, then this is called indirect recursion. For example: function A calls function B and
Function B calls function A.
Output:
120
Arrays in C++
int arr[5];
arr[0] = 10;
arr[1] = 20;
arr[2] = 30;
arr[3] = 40;
arr[4] = 50;
Method 2:
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;
}
int arr[2][3];
int arr[2][2][2];
Lets see how to declare, initialize and access Two Dimensional Array elements.
int myarray[2][3];
Initialization:
We can initialize the array in many ways:
Method 1:
Method 2:
This way of initializing is preferred as you can visualize the rows and columns here.
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
Lets see how to declare, initialize and access Three Dimensional Array elements.
int myarray[2][3][2];
Initialization:
We can initialize the array in many ways:
Method 1:
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}},
#include <iostream>
using namespace std;
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
You can pass array as an argument to a function just like you pass variables as arguments. In
order to pass array to the function you just need to mention the array name during function
call like this:
function_name(array_name);
In this example, we are passing two arrays a & b to the function sum(). This function adds the
corresponding elements of both the arrays and display them.
#include <iostream>
using namespace std;
/* This function adds the corresponding
* elements of both the arrays and
* displays it.
*/
void sum(int arr1[], int arr2[]){
int temp[5];
Output:
11
22
33
44
55
In this example we are passing a multidimensional array to the function square which displays the
square of each element.
#include <iostream>
#include <cmath>
using namespace std;
/* This method prints the square of each
* of the elements of multidimensional array
*/
void square(int arr[2][3]){
int temp;
for(int i=0; i<2; i++){
for(int j=0; j<3; j++){
temp = arr[i][j];
cout<<pow(temp, 2)<<endl;
}
}
}
int main(){
int arr[2][3] = {
{1, 2, 3},
{4, 5, 6}
};
square(arr);
return 0;
}
Output:
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
Lets discuss these two ways of creating string first and then we will see which method is better
and why.
#include <iostream>
using namespace std;
int main(){
char book[50] = "A Song of Ice and Fire";
cout<<book;
return 0;
}
Output:
#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;
}
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.
#include <iostream>
using namespace std;
int main(){
char book[50];
cout<<"Enter your favorite book name:";
Output:
1) Size of the char array is fixed, which means the size of the string created through it is fixed in
size, more memory cannot be allocated to it during runtime. For example, lets say you have
created an array of character with the size 10 and user enters the string of size 15 then the last
five characters would be truncated from the string.
On the other hand if you create a larger array to accommodate user input then the memory is
wasted if the user input is small and array is much larger then what is needed.
2) In this method, you can only use the in-built functions created for array which don’t help
much in string manipulation.
#include<iostream>
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
an 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 (&).
Example of Pointer
#include <iostream>
using namespace std;
int main(){
//Pointer declaration
int *p, var=101;
//Assignment
p = &var;
Output:
While handling arrays with pointers you need to take care few things. First and very important
point to note regarding arrays is that the array name alone represents the base address of array so
while assigning the address of array to pointer don’t use ampersand sign(&). Do it like this:
Correct: Because arr represent the address of array.
p = arr;
Incorrect:
p = &arr;
Output:
1
2
3
4
5
6
When we are accessing the value of a variable through pointer, sometimes we just need to
increment or decrement the value of variable though it or we may need to move the pointer to
next int position(just like we did above while working with arrays). The ++ operator is used for
this purpose. One of the example of ++ operator we have seen above where we traversed the
/* All the following three cases are same they increment the value
* of variable that the pointer p points.
*/
++*p;
++(*p);
++*(p);
#include <iostream>
using namespace std;
class Demo {
private:
int num;
char ch;
public:
void setMyValues(int num, char ch){
this->num =num;
this->ch=ch;
}
void displayMyValues(){
cout<<num<<endl;
cout<<ch;
}
};
int main(){
Demo obj;
obj.setMyValues(100, 'A');
obj.displayMyValues();
Output:
100
A
Another example of using this pointer is to return the reference of current object so that you can
chain function calls, this way you can call all the functions for the current object in one go.
Another important point to note in this program is that I have incremented the value of object’s
num in the second function and you can see in the output that it actually incremented the value
that we have set in the first function call. This shows that the chaining is sequential and the
changes made to the object’s data members retains for further chaining calls.
#include <iostream>
using namespace std;
class Demo {
private:
int num;
char ch;
public:
Demo &setNum(int num){
this->num =num;
return *this;
}
Demo &setCh(char ch){
this->num++;
this->ch =ch;
return *this;
}
void displayMyValues(){
cout<<num<<endl;
cout<<ch;
}
};
int main(){
Demo obj;
//Chaining calls
obj.setNum(100).setCh('A');
obj.displayMyValues();
return 0;
}
Output:
101
A
Object oriented programming is a way of solving complex problems by breaking them into
smaller problems using objects. Before Object Oriented Programming (commonly referred as
OOP), programs were written in procedural language, they were nothing but a long list of
instructions. On the other hand, the OOP is all about creating objects that can interact with each
other, this makes it easier to develop programs in OOP as we can understand the relationship
between them.
In Object oriented programming we write programs using classes and objects utilising features of
OOPs such as abstraction, encapsulation, inheritance and polymorphism
A class is like a blueprint of data member and functions and object is an instance of class. For
example, lets say we have a class Car which has data members (variables) such as speed,
weight, price and functions such as gearChange(), slowDown(), brake() etc. Now lets say I create
a object of this class named FordFigo which uses these data members and functions and give
them its own values. Similarly we can create as many objects as we want using the
blueprint(class).
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
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
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;
}
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. Lets take a simple
example to understand the working of constructor.
Read the comments in the following program to understand each part of the program.
#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;
Output:
num: 100
ch: A
Now that we know what is constructor, lets discuss how a constructor is different from member
function of the class.
1) Constructor doesn’t have a return type. Member function has a return type.
2) Constructor is automatically called when we create the object of the class. Member function
needs to be called explicitly using object of class.
3) When we do not create any constructor in our class, C++ compiler generates a default
constructor and insert it into our code. The same does not apply to member functions.
This is how a compiler generated default constructor looks:
class XYZ
{
....
XYZ()
{
//Empty no code
}
};
There are two types of constructor in C++. 1) Default constructor 2) Parameterized constructor
1) Default Constructor
#include <iostream>
using namespace std;
class Website{
public:
//Default constructor
Website() {
cout<<"Welcome to BeginnersBook"<<endl;
}
};
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
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){
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(){
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, 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;
};
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:
Similarly I can set and get the values of other data members of the structure for every student.
Lets see a complete example to put this up all together:
Output:
In this previous tutorial we learnt about structures, the compound data type that groups different
types of variables. In this tutorial, we will learn how to pass structures as an argument to the
function and how to return the structure from the function.
Here we have a function printStudentInfo() which takes structure Student as an argument and prints
the details of student using structure varaible. The important point to note here is that you should
always declare the structure before function declarations, otherwise you will get compilation
error.
#include <iostream>
using namespace std;
struct Student{
char stuName[30];
int stuRollNo;
int stuAge;
};
void printStudentInfo(Student);
int main(){
Student s;
cout<<"Enter Student Name: ";
cin.getline(s.stuName, 30);
cout<<"Enter Student Roll No: ";
cin>>s.stuRollNo;
cout<<"Enter Student Age: ";
cin>>s.stuAge;
printStudentInfo(s);
return 0;
}
void printStudentInfo(Student s){
cout<<"Student Record:"<<endl;
cout<<"Name: "<<s.stuName<<endl;
cout<<"Roll No: "<<s.stuRollNo<<endl;
cout<<"Age: "<<s.stuAge;
}
Output:
In this example we have two functions one gets the values from user, assign them to structure
members and returns the structure and the other function takes that structure as argument and
print the details.
#include <iostream>
using namespace std;
struct Student{
char stuName[30];
int stuRollNo;
int stuAge;
};
Student getStudentInfo();
void printStudentInfo(Student);
int main(){
Student s;
s = getStudentInfo();
printStudentInfo(s);
return 0;
}
/* This function prompt the user to input student
* details, stores them in structure members
* and returns the structure
*/
Student getStudentInfo(){
Student s;
cout<<"Enter Student Name: ";
cin.getline(s.stuName, 30);
cout<<"Enter Student Roll No: ";
cin>>s.stuRollNo;
cout<<"Enter Student Age: ";
cin>>s.stuAge;
return s;
}
void printStudentInfo(Student s){
cout<<"Student Record:"<<endl;
cout<<"Name: "<<s.stuName<<endl;
cout<<"Roll No: "<<s.stuRollNo<<endl;
cout<<"Age: "<<s.stuAge;
}
Output:
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 a
Enumeration.
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.
As we have seen in the above example that I have declared the enum variable dir during enum
declaration, there is another way to declare an enum variable.
#include <iostream>
using namespace std;
enum direction {East, West, North, South};
int main(){
direction dir;
dir = South;
cout<<dir;
return 0;
}
Output:
Another important place where they are used frequently are switch case statements, where all the
values that case blocks expect can be defined in an enum. This way we can ensure that the enum
variable that we pass in switch parenthesis is not taking any random value that it shouldn’t
accept.
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.
Syntax of Inheritance
class parent_class
{
//Body of parent class
};
class child_class : access_modifier parent_class
{
The main advantages of inheritance are code reusability and readability. When child class
inherits the properties and functionality of parent class, we need not to write the same code again
in child class. This makes it easier to reuse the code, makes us write the less code and the code
becomes much more readable.
Lets take a real life example to understand this: Lets assume that Human is a class that has
properties such as height, weight, colour etc and functionality such as eating(), sleeping(),
dreaming(), working() etc.
Now we want to create Male and Female class, these classes are different but since both Male and
Female are humans they share some common properties and behaviours (functionality) so they
can inherit those properties and functionality from Human class and rest can be written in their
class separately.
This approach makes us write less code as both the classes inherited several properties and
functions from base class thus we didn’t need to re-write them. Also, this makes it easier to read
the code.
Inheritance Example
Another important point to note is that when we create the object of child class it calls the
constructor of child class and child class constructor automatically calls the constructor of base
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";
Output:
1) Single inheritance
2) Multilevel inheritance
3) Multiple inheritance
4) Hierarchical inheritance
5) Hybrid inheritance
Single inheritance
B inherits A
#include <iostream>
using namespace std;
class A {
public:
A(){
cout<<"Constructor of A class"<<endl;
}
};
class B: public A {
public:
B(){
cout<<"Constructor of B class";
}
};
int main() {
//Creating object of class B
B obj;
Output:
Constructor of A class
Constructor of B class
2)Multilevel Inheritance
#include <iostream>
using namespace std;
class A {
public:
A(){
cout<<"Constructor of A class"<<endl;
}
};
class B: public A {
public:
B(){
cout<<"Constructor of B class"<<endl;
}
};
class C: public B {
public:
C(){
cout<<"Constructor of C class"<<endl;
}
};
int main() {
//Creating object of class C
C obj;
return 0;
}
Output:
Constructor of A class
Constructor of B class
Constructor of C class
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:
#include <iostream>
using namespace std;
class A {
public:
A(){
cout<<"Constructor of A class"<<endl;
}
};
class B {
public:
B(){
cout<<"Constructor of B class"<<endl;
}
};
class C: public A, public B {
public:
C(){
cout<<"Constructor of C class"<<endl;
}
};
int main() {
//Creating object of class C
C obj;
return 0;
}
Constructor of A class
Constructor of B class
Constructor of C class
4)Hierarchical Inheritance
In this type of inheritance, one parent class has more than one child class. For example:
#include <iostream>
using namespace std;
class A {
public:
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.
In this example, we have two functions with same name but different number of arguments.
Based on how many parameters we pass during function call determines which function is to be
called, this is why it is considered as an example of polymorphism because in different
#include <iostream>
using namespace std;
class Add {
public:
int sum(int num1, int num2){
return num1+num2;
}
int sum(int num1, int num2, int num3){
return num1+num2+num3;
}
};
int main() {
Add obj;
//This will call the first function
cout<<"Output: "<<obj.sum(10, 20)<<endl;
//This will call the second function
cout<<"Output: "<<obj.sum(11, 22, 33);
return 0;
}
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.
Output:
Function overloading is a C++ programming feature that allows us to have more than one
function having same name but different parameter list, when I say parameter list, it means the
data type and sequence of the parameters, for example the parameters list of a function
myfuncn(int a, float b) is (int, float) which is different from the function myfuncn(float a, int b) parameter
list (float, int). Function overloading is a compile-time polymorphism.
Now that we know what is parameter list lets see the rules of overloading: we can have following
functions in the same scope.
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:
This is not allowed as the parameter list is same. Even though they have different return types, its
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
As I mentioned in the beginning of this guide that functions having different return types and
same parameter list cannot be overloaded. However if the functions have different parameter list
then they can have same or different return types to be eligible for overloading. In short the
return type of a function
does not play any role in function overloading. All that matters is the parameter list of function.
#include <iostream>
using namespace std;
class DemoClass {
public:
int demoFunction(int i) {
return i;
}
Output:
100
5006.52
The main advantage of function overloading is to the improve the code readability and allows
code reusability. In the example 1, we have seen how we were able to have more than one
function for the same task(addition) with different parameters, this allowed us to add two integer
numbers as well as three integer numbers, if we wanted we could have some more functions with
same name and four or five arguments.
Imagine if we didn’t have function overloading, we either have the limitation to add only two
integers or we had to write different name functions for the same task addition, this would reduce
the code readability and reusability.
Function overriding is a feature that allows us to have a same function in child class which is
already present in the parent class. A child class inherits the data members and member functions
of parent class, but when you want to override a functionality in the child class then you can use
function overriding. It is like creating a new version of an old function, in the child class.
To override a function you must have the same signature in child class. By signature I mean the
data type and sequence of parameters. Here we don’t have any parameter in the parent function
so we didn’t use any parameter in the child function.
#include <iostream>
using namespace std;
class BaseClass {
public:
void disp(){
cout<<"Function of Parent Class";
}
Output:
Note: In function overriding, the function in parent class is called the overridden function and
function in child class is called overriding function.
As we have seen above that when we make the call to function (involved in overriding), the child
class function (overriding function) gets called. What if you want to call the overridden function
by using the object of child class. You can do that by creating the child class object in such a
way that the reference of parent class points to it. Lets take an example to understand it.
#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:
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();
Function overloading and Function overriding both are examples of polymorphism but they are
completely different. Before we discuss the difference between them, lets discuss a little bit
about them first.
Function Overloading
Function overloading is a feature that allows us to have same function more than once in a
program. Overloaded functions have same name but their signature must be different.
Example:
Here we have the same function sum declared four times with different signatures. Based on the
parameters we pass, while calling function sum, decides which method is to be called. This
happens during compilation, which is why it is also known as compile time polymorphism. If
you are wondering why I have suffixed each floating point value with “f” letter in the example
below, during function call then refer this: function overloading float issue.
#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;
Output:
28.4
300
120.7
120.8
Function Overriding
#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();
Output:
Now that we understand what is function overloading and overriding in C++ programming, lets
see the difference between them:
1) Function Overloading happens in the same class when we declare same functions with
different arguments in the same class. Function Overriding is happens in the child class when
child class overrides parent class function.
2) In function overloading function signature should be different for all the overloaded functions.
In function overriding the signature of both the functions (overriding function and overridden
function) should be same.
3) Overloading happens at the compile time thats why it is also known as compile time
polymorphism while overriding happens at run time which is why it is known as run time
polymorphism.
4) In function overloading we can have any number of overloaded functions. In function
overriding we can have only one overriding function in the child class.
In this guide, we will see what are virtual functions and why we use them. When we declare a
function as virtual in a class, all the sub classes that override this function have their function
implementation as virtual by default (whether they mark them virtual or not). Why we declare a
function virtual? To let compiler know that the call to this function needs to be resolved at
runtime (also known as late binding and dynamic linking) so that the object type is determined
and the correct version of the function is called.
Lets take an example to understand what happens when we don’t mark a overridden function as
virtual.
You may be thinking why I have created the pointer, I could have simply created the object of
child class like this: Dog obj; and assigned the Dog instance to it. Well, in this example I have
only one child class but when we a big project having several child classes, creating the object of
child class separately is not recommended as it increases the complexity and the code become
error prone. More clarity to this after this example.
#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:
#include<iostream>
using namespace std;
//Parent class or super class or base class
class Animal{
public:
virtual void animalSound(){
cout<<"This is a generic Function";
}
};
Output:
Woof
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 feature of Object Oriented Programming(OOPs)
that helps in data hiding.
To do this:
1) Make all the 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.
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.
*/
Output:
100
A
Abstraction is one of the feature of Object Oriented Programming, where you show only relevant
details to the user and hide irrelevant details. For example, when you send an email to someone
you just click send and you get the success message, what actually happens when you click send,
how data is transmitted over network to the recipient is hidden from you (because it is irrelevant
to you).
Let’s see how this can be achieved in a C++ program using access specifiers:
Abstraction Example
#include <iostream>
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:
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.
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.
Let’s understand this with the help of a real life example. Lets 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.
1) As we have seen that any class that has a pure virtual function is an abstract class.
2) We cannot create the instance of abstract class. For example: If I have written this line Animal
obj; in the above program, it would have caused compilation error.
3) We can create pointer and reference of base abstract class points to the instance of child class.
For example, this is valid:
As we know that a class cannot access the private members of other class. Similarly a class that
doesn’t inherit another class cannot access its protected members.
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.
In this example we have two classes XYZ and ABC. The XYZ class has two private data members
ch and num, this class declares ABC as friend class. This means that ABC can access the private
members of XYZ, the same has been demonstrated in the example where the function disp() of
ABC class accesses the private members num and ch. In this example we are passing object as an
argument to the function.
#include <iostream>
using namespace std;
class XYZ {
private:
char ch='A';
int num = 11;
public:
/* This statement would make class ABC
* a friend class of XYZ, this means that
* ABC can access the private and protected
* members of XYZ 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:
Output:
100
Z