C++ Notes
C++ Notes
C++ Notes
C++ history
History of C++ language is interesting to know. Here we
are going to discuss brief history of C++ language.
C++ programming is "relative" (called a superset) of C, it means any valid C program is also
a valid C++ program.
Let's see the programming languages that were developed before C++ language.
C++ Features
C++ is object oriented programming language. It provides a lot of features that are given
below.
Simple
Rich Library
Memory Management
Fast Speed
Pointers
Recursion
Extensible
Object Oriented
Compiler based
1) Simple
C++ is a simple language in the sense that it provides structured approach (to break the
problem into parts), rich set of library functions, data types etc.
Unlike assembly language, c programs can be executed in many machines with little bit or
no change. But it is not platform-independent.
C++ is also used to do low level programming. It is used to develop system applications such
as kernel, driver etc. It also supports the feature of high level language. That is why it is
known as mid-level language.
C++ is a structured programming language in the sense that we can break the program into
parts using functions. So, it is easy to understand and modify.
5) Rich Library
C++ provides a lot of inbuilt functions that makes the development fast.
6) Memory Management
It supports the feature of dynamic memory allocation. In C++ language, we can free the
allocated memory at any time by calling the free() function.
7) Speed
8) Pointer
C++ provides the feature of pointers. We can directly interact with the memory by using
the pointers. We can use pointers for memory, structures, functions, array etc.
9) Recursion
In C++, we can call the function within the function. It provides code reusability for every
function.
10) Extensible
C++ is object oriented programming language. OOPs makes development and maintenance
easier where as in Procedure-oriented programming language it is not easy to manage if
code grows as project size grows.
C++ is a compiler based programming language, it means without compilation no C++ program
can be executed. First we need to compile our program using compiler and then we can
execute our program.
C++ Variable
A variable is a name of memory location. It is used to store data. Its value can be changed
and it can be reused many times.
It is a way to represent memory location through symbol so that it can be easily identified.
type variable_list;
int x=10;
float y;
char z;
Here, x, y, z are variables and int, float, char are data types.
We can also provide values while declaring the variables as given below:
float f=30.8;
char c='A';
A variable name can start with alphabet and underscore only. It can't start with digit.
A variable name must not be any reserved word or keyword e.g. char, float etc.
The basic data types are integer-based and floating-point based. C++ language supports
both signed and unsigned literals.
The memory size of basic data types may change according to 32 or 64 bit operating
system.
Let's see the basic data types. It size is given according to 32 bit OS.
double 8 byte
C++ Keywords
A keyword is a reserved word. You cannot use it as a variable name, constant name etc. A
list of 32 Keywords in C++ Language which are also available in C language are given below.
A list of 30 Keywords in C++ Language which are not available in C language are given below.
C++ Operators
Operators are symbols that perform operations on variables and values. For example, + is
an operator used for addition, while - is an operator used for subtraction.
Arithmetic Operators
Assignment Operators
Relational Operators
Logical Operators
Bitwise Operators
Other Operators
Arithmetic operators are used to perform arithmetic operations on variables and data. For
example,
a + b;
Here, the + operator is used to add two variables a and b. Similarly there are various other
arithmetic operators in C++.
Operator Operation
+ Addition
- Subtraction
* Multiplication
/ Division
-- decreases it by 1
In C++, assignment operators are used to assign values to variables. For example,
// assign 5 to a
a = 5;
= a = b; a = b;
+= a += b; a = a + b;
-= a -= b; a = a - b;
*= a *= b; a = a * b;
/= a /= b; a = a / b;
%= a %= b; a = a % b;
A relational operator is used to check the relationship between two operands. For example,
a > b;
Logical operators are used to check whether an expression is true or false. If the
expression is true, it returns 1 whereas if the expression is false, it returns 0.
Logical OR.
|| expression1 || expression2 True if at least one of the operands is
true.
Logical NOT.
! !expression
True only if the operand is false.
In C++, bitwise operators are used to perform operations on individual bits. They can only
be used alongside char and int data types.
Operator Description
| Binary OR
^ Binary XOR
~ Binary One's Complement
Here's a list of some other common operators available in C++. We will learn about them in
later tutorials.
C++ Identifiers
C++ identifiers in a program are used to refer to the name of the variables, functions,
arrays, or other user-defined data types created by the programmer. They are the basic
requirement of any language. Every language has its own rules for naming the identifiers.
In short, we can say that the C++ identifiers represent the essential elements in a program
which are given below:
Constants
Variables
Functions
Labels
Some naming rules are common in both C and C++. They are as follows:
The identifier name cannot start with a digit, i.e., the first letter should be alphabetical.
After the first letter, we can use letters, digits, or underscores.
In C++, uppercase and lowercase letters are distinct. Therefore, we can say that C++
identifiers are case-sensitive.
C++ Program
Before starting the abcd of C++ language, you need to learn how to write, compile and run
the first C++ program.
To write the first C++ program, open the C++ console and write the following code:
#include <iostream.h>
#include<conio.h>
void main()
clrscr();
getch();
#include <conio.h> includes the console input output library functions. The getch() function
is defined in conio.h file.
void main() The main() function is the entry point of every program in C++ language. The
void keyword specifies that it returns no value.
cout << "Welcome to C++ Programming." is used to print the data "Welcome to C++
Programming." on the console.
getch() The getch() function asks for a single character. Until you press any key, it blocks
the screen.
How to compile and run the C++ program
There are 2 ways to compile and run the C++ program, by menu and by shortcut.
By menu
Now click on the compile menu then compile sub menu to compile the c++ program.
Then click on the run menu then run sub menu to run the c++ program.
By shortcut
Or, press ctrl+f9 keys compile and run the program directly.
#include <iostream>
int main()
return 0;
Output
Hello, World!
#include <iostream>
int main()
// Prints sum
cout << firstNumber << " + " << secondNumber << " = " << sumOfTwoNumbers;
return 0;
Output
4+5=9
#include <iostream>
int main()
cout << "Size of char: " << sizeof(char) << " byte" << endl;
cout << "Size of int: " << sizeof(int) << " bytes" << endl;
cout << "Size of float: " << sizeof(float) << " bytes" << endl;
cout << "Size of double: " << sizeof(double) << " bytes" << endl;
return 0;
Output
#include <iostream>
int main()
return 0;
Output
Enter dividend: 13
Enter divisor: 4
Quotient = 3
Remainder = 1
#include <iostream>
int main()
cout << "a = " << a << ", b = " << b << endl;
temp = a;
a = b;
b = temp;
cout << "a = " << a << ", b = " << b << endl;
return 0;
Output
Before swapping.
a = 5, b = 10
After swapping.
a = 10, b = 5
int main()
char c;
cout << "ASCII Value of " << c << " is " << int(c);
return 0;
Output
Enter a character: p
Control Statement
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 statement consists a condition, followed by statement or a set of statements as shown
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.
#include <iostream>
int main() {
int number;
if (number > 0) {
cout << "You entered a positive integer: " << number << endl;
return 0;
}
Output
Enter an integer: 5
Sometimes you have a condition and you want to execute a block of code if condition is
true and execute another piece of code if the same condition is false. This can be achieved
in C++ using if-else statement.
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.
#include <iostream>
int main() {
int number;
cout << "Enter an integer: ";
if (number >= 0) {
cout << "You entered a positive integer: " << number << endl;
else {
cout << "You entered a negative integer: " << number << endl;
return 0;
Output
Enter an integer: 4
#include <iostream>
int main(){
int num=66;
}
else {
return 0;
#include <iostream>
int main () {
int num;
cin>>num;
if (num % 2 == 0)
else
return 0;
Output:
Enter a number:11
It is odd number
if(condition1){
}else if(condition2){
else if(condition3){
...
else
{
//code to be executed if all the conditions are false
#include <iostream>
int main () {
int num;
cin>>num;
cout<<"wrong number";
cout<<"Fail";
cout<<"D Grade";
cout<<"C Grade";
}
else if (num >= 70 && num < 80)
cout<<"B Grade";
cout<<"A Grade";
cout<<"A+ Grade";
Output:
C Grade
#include <iostream>
int main()
return 0;
Output
8.3
-4.2
#include <iostream>
int main()
char c;
cin >> c;
if (isLowercaseVowel || isUppercaseVowel)
else
return 0;
Output
Enter an alphabet: u
u is a vowel.
C++ switch
The C++ switch statement executes one
statement from multiple conditions. It is like if-
else-if ladder statement in C++.
switch(expression){
case value1:
//code to be executed;
break;
case value2:
//code to be executed;
break;
......
default:
break;
#include <iostream>
int main () {
int num;
cin>>num;
switch (num)
Output:
Enter a number:
10
It is 10
#include <iostream>
int main() {
char oper;
switch (oper) {
case '+':
cout << num1 << " + " << num2 << " = " << num1 + num2;
break;
case '-':
cout << num1 << " - " << num2 << " = " << num1 - num2;
break;
case '*':
cout << num1 << " * " << num2 << " = " << num1 * num2;
break;
case '/':
cout << num1 << " / " << num2 << " = " << num1 / num2;
break;
default:
break;
return 0;
Output 1
2.3
4.5
Example
#include <iostream>
int main () {
switch(grade) {
case 'A' :
cout << "Excellent!" << endl;
break;
case 'B' :
case 'C' :
break;
case 'D' :
break;
case 'F' :
break;
default :
return 0;
You passed
Your grade is D
C++ For Loop
The C++ for loop is used to iterate a part of the
program several times. If the number of
iteration is fixed, it is recommended to use for
loop than while or do-while loops.
//code to be executed
Flowchart:
#include <iostream>
int main() {
for(int i=1;i<=10;i++){
cout<<i <<"\n";
Output:
4
5
10
#include <iostream>
int main() {
sum = 0;
sum += count;
return 0;
Output
Sum = 55
Example: Find Factorial of a given number
#include <iostream>
int main()
int n;
cin >> n;
if (n < 0)
else {
factorial *= i;
cout << "Factorial of " << n << " = " << factorial;
return 0;
Output
Factorial of 12 = 479001600
Example 1: Fibonacci Series up to n number of terms
#include <iostream>
int main() {
int n, t1 = 0, t2 = 1, nextTerm = 0;
cin >> n;
if(i == 1) {
continue;
if(i == 2) {
continue;
nextTerm = t1 + t2;
t1 = t2;
t2 = nextTerm;
return 0;
}
Output
**
***
****
*****
Source Code
#include <iostream>
int main()
int rows;
}
return 0;
12
123
1234
12345
Source Code
#include <iostream>
int main()
int rows;
return 0;
}
*****
****
***
**
Source Code
#include <iostream>
int main()
int rows;
return 0;
}
Example 5: Inverted half pyramid using numbers
12345
1234
123
12
Source Code
#include <iostream>
int main()
int rows;
return 0;
}
Example : Print Floyd's Triangle.
23
456
7 8 9 10
Source Code
#include <iostream>
int main()
++number;
return 0;
}
Example: C++ program to print full star pyramid pattern
***
*****
*******
*********
#include <iostream>
int main()
return 0;
while (condition) {
Here,
#include <iostream>
int main() {
int i = 1;
while (i <= 5) {
++i;
return 0;
Output
12345
#include <iostream>
int main() {
int number;
int sum = 0;
sum += number;
// take input again if the number is positive
return 0;
Output
Enter a number: 6
Enter a number: 12
Enter a number: 7
Enter a number: 0
Enter a number: -2
The sum is 25
#include <iostream>
int main(){
int i=1;
*/
while(i<=6){
Output:
do {
// body of loop;
while (condition);
Here,
#include <iostream>
int main() {
int i = 1;
do {
++i;
return 0;
Output
12345
#include <iostream>
int main() {
int number = 0;
int sum = 0;
do {
sum += number;
return 0;
Output
Enter a number: 6
Enter a number: 12
Enter a number: 7
Enter a number: 0
Enter a number: -2
The sum is 25
C++ Break Statement
The C++ break is used to break loop or
switch statement. It breaks the current
flow of the program at the given
condition. In case of inner loop, it breaks
only inner loop.
jump-statement;
break;
Flowchart:
Let's see a simple example of C++ break statement which is used inside the loop.
#include <iostream>
int main() {
if (i == 5)
break;
cout<<i<<"\n";
Output:
1
2
#include <iostream>
int main(){
while(num<=200) {
if (num==12) {
break;
num++;
return 0;
Output:
#include <iostream>
int main(){
int var;
cout<<"var: "<<var<<endl;
if (var==197) {
break;
return 0;
Output:
var: 200
var: 199
var: 198
var: 197
#include <iostream>
int main(){
int num=2;
switch (num) {
break;
break;
break;
return 0;
Output:
Case 2
jump-statement;
continue;
#include <iostream>
int main()
for(int i=1;i<=10;i++){
if(i==5){
continue;
cout<<i<<"\n";
Output:
8
9
10
#include <iostream>
int main(){
int j=6;
while (j >=0) {
if (j==4) {
j--;
continue;
cout<<"Value of j: "<<j<<endl;
j--;
return 0;
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
Example of continue in do-While loop
#include <iostream>
int main(){
int j=4;
do {
if (j==7) {
j++;
continue;
j++;
}while(j<10);
return 0;
Output:
j is: 4
j is: 5
j is: 6
j is: 8
j is: 9
Program to Check Armstrong Number
#include <iostream>
int main()
num = origNum;
while(num != 0)
num /= 10;
if(sum == origNum)
else
return 0;
Output
goto label_name;
Program structure:
label1:
...
...
goto label2;
...
..
label2:
...
#include <iostream>
int main(){
if (num % 2==0){
goto print;
else {
cout<<"Odd Number";
}
print:
cout<<"Even Number";
return 0;
Output:
Enter a number: 42
Even Number
# include <iostream>
int main()
int i, n;
cin >> n;
{
// Control of the program move to jump:
goto jump;
sum += num;
jump:
return 0;
Output
Average = 3.95
#include <iostream>
int main()
ineligible:
int age;
cin>>age;
goto ineligible;
else
Output:
16
22
In C++ std::array is a container that encapsulates fixed size arrays. In C++, array index
starts from 0. We can store only fixed set of elements in C++ array.
Random Access
Fixed size
Multidimensional Array
C++ Array Declaration
dataType arrayName[arraySize];
For example,
int x[6];
Here,
In C++, each element in an array is associated with a number. The number is known as an
array index. We can access elements of an array by using those indices.
array[index];
The array indices start with 0. Meaning x[0] is the first element stored at index 0.
If the size of an array is n, the last element is stored at index (n-1). In this
example, x[5] is the last element.
Elements of an array have consecutive addresses. For example, suppose the starting
address of x[0] is 2120d. Then, the address of the next element x[1] will be 2124d, the
address of x[2] will be 2128d and so on.
Here, the size of each element is increased by 4. This is because the size of int is 4 bytes.
Here, we have not mentioned the size of the array. In such cases, the compiler
automatically computes the size.
#include <iostream>
int main()
int n, i;
cin >> n;
cin >> n;
sum += num[i];
average = sum / n;
return 0;
Output
5. Enter number: 33
6. Enter number: 45.6
Average = 27.69
#include <iostream>
int main()
int i, n;
float arr[100];
cin >> n;
arr[0] = arr[i];
}
cout << "Largest element = " << arr[0];
return 0;
Output
Enter Number 3: 50
#include <iostream>
int main()
//traversing array
{
cout<<arr[i]<<"\n";
Output
10
20
30
In C++, we can create an array of an array, known as a multidimensional array. For example:
int x[3][4];
We can think of this array as a table with 3 rows and each row has 4 columns as shown
below.
Elements in two-dimensional
array in C++ Programming
Three-dimensional arrays also work in a similar way. For example:
float x[2][4][3];
We can find out the total number of elements in the array simply by multiplying its
dimensions:
2 x 4 x 3 = 24
Like a normal array, we can initialize a multidimensional array in more than one way.
The above method is not preferred. A better way to initialize this array with the same
array elements is given below:
This array has 2 rows and 3 columns, which is why we have two rows of elements with 3
elements each.
#include <iostream>
int main() {
{4, 0},
{9, 1}};
cout << "test[" << i << "][" << j << "] = " << test[i][j] << endl;
return 0;
Output
test[0][0] = 2
test[0][1] = -5
test[1][0] = 4
test[1][1] = 0
test[2][0] = 9
test[2][1] = 1
#include <iostream>
int main() {
int numbers[2][3];
cout << "numbers[" << i << "][" << j << "]: " << numbers[i][j] << endl;
return 0;
Output
Enter 6 numbers:
numbers[0][0]: 1
numbers[0][1]: 2
numbers[0][2]: 3
numbers[1][0]: 4
numbers[1][1]: 5
numbers[1][2]: 6
Example: Add Two Matrices using Multi-dimensional Arrays
#include <iostream>
int main()
cin >> r;
cin >> c;
cout << endl << "Enter elements of 1st matrix: " << endl;
cout << "Enter element a" << i + 1 << j + 1 << " : ";
cout << endl << "Enter elements of 2nd matrix: " << endl;
for(i = 0; i < r; ++i)
cout << "Enter element b" << i + 1 << j + 1 << " : ";
cout << endl << "Sum of two matrix is: " << endl;
if(j == c - 1)
return 0;
Output
-1 -4
13 10
#include <iostream>
int main() {
cout << "Enter element a" << i + 1 << j + 1 << ": ";
if (j == column - 1)
transpose[j][i] = a[i][j];
}
if (j == row - 1)
return 0;
Output
Entered Matrix:
1 2 9
0 4 7
Transpose of Matrix:
1 0
2 4
9 7
C++ Strings
In this tutorial, you'll learn to handle strings in C++. You'll learn to declare them, initialize
them and use them for various input/output operations.
String is a collection of characters. There are two types of strings commonly used in C++
programming language:
Strings that are objects of string class (The Standard C++ Library string class)
C-strings
In C programming, the collection of characters is stored in the form of arrays. This is also
supported in C++ programming. Hence it's called C-strings.
C-strings are arrays of type char terminated with null character, that is, \0 (ASCII value
of null character is 0).
How to define a C-string?
Although, "C++" has 3 character, the null character \0 is added to the end of the string
automatically.
Like arrays, it is not necessary to use all the space allocated for the string. For example:
#include <iostream>
int main()
char str[100];
return 0;
Output
This is because the extraction operator >> works as scanf() in C and considers a space " "
has a terminating character.
#include <iostream>
int main()
char str[100];
return 0;
Output
#include <iostream>
int main()
int count = 0;
if (str[i] == checkCharacter)
++ count;
}
cout << "Number of " << checkCharacter << " = " << count;
return 0;
Output
Number of a = 2
This program takes a string (object) input from the user and removes all characters
except alphabets.
#include <iostream>
int main() {
string line;
getline(cin, line);
if ((line[i] >= 'a' && line[i] <= 'z') || (line[i] >= 'A' && line[i] <= 'Z')) {
}
line = temp;
return 0;
Output
#include <iostream>
int main() {
return 0;
Output
String Length = 15
Example 1: Concatenate String Objects
#include <iostream>
int main()
result = s1 + s2;
return 0;
Output
This program takes a C-style string from the user and calculates the number of vowels,
consonants, digits and white-spaces.
#include <iostream>
int main()
char line[150];
cin.getline(line, 150);
line[i]=='U')
++vowels;
++consonants;
}
++digits;
++spaces;
return 0;
Output
Vowels: 7
Consonants: 10
Digits: 1
White spaces: 6
C++ Functions
A function is a block of code that performs a specific task.
Suppose we need to create a program to create a circle and color it. We can create two
functions to solve this problem:
Dividing a complex problem into smaller chunks makes our program easy to understand and
reusable.
A user-defined function groups code to perform a specific task and that group of code is
given a name (identifier).
When the function is invoked from any part of the program, it all executes the codes
defined in the body of the function.
// function body
// function declaration
void greet() {
Here,
Note: We will learn about returnType and parameters later in this tutorial.
Calling a Function
int main() {
// calling a function
greet();
}
How Function works in C++
#include <iostream>
// declaring a function
void greet() {
int main() {
greet();
return 0;
}
Output
Hello there!
Function Parameters
int main() {
int n = 7;
printNum(n);
return 0;
#include <iostream>
int main() {
int num1 = 5;
displayNum(num1, num2);
return 0;
Output
In the above program, we have used a function that has one int parameter and
one double parameter.
We then pass num1 and num2 as arguments. These values are stored by the function
parameters n1 and n2 respectively.
C++ function
with parameters
Note: The type of the arguments passed while calling the function must match with the
corresponding parameters defined in the function declaration.
Return Statement
In the above programs, we have used void in the function declaration. For example,
void displayNumber() {
// code
It's also possible to return a value from a function. For this, we need to specify
the returnType of the function during function declaration.
Then, the return statement can be used to return a value from a function.
For example,
return (a + b);
Here, we have the data type int instead of void. This means that the function returns
an int value.
The code return (a + b); returns the sum of the two parameters as the function value.
The return statement denotes that the function has ended. Any code after return inside
the function is not executed.
#include <iostream>
// declaring a function
return (a + b);
int main() {
int sum;
return 0;
}
Output
100 + 78 = 178
In the above program, the add() function is used to find the sum of two numbers.
We pass two int literals 100 and 78 while calling the function.
We store the returned value of the function in the variable sum, and then we print it.
Working of
C++ Function with return statement
Notice that sum is a variable of int type. This is because the return value of add() is
of int type.
Function Prototype
In C++, the code of function declaration should be before the function call. However, if we
want to define a function after the function call, we need to use the function prototype.
For example,
// function prototype
int main() {
// calling the function before declaration.
add(5, 3);
return 0;
// function definition
This provides the compiler with information about the function name and its parameters.
That's why we can use the code to call a function before the function has been defined.
#include <iostream>
// function prototype
int sum;
return 0;
// function definition
return (a + b);
Output
100 + 78 = 178
The above program is nearly identical to Example 3. The only difference is that here, the
function is defined after the function call.
Functions make the code reusable. We can declare them once and use them multiple times.
Functions make the program easier as each small task is divided into a function.
Programmers can use library functions by invoking the functions directly; they don't need
to write the functions themselves.
Some common library functions in C++ are sqrt(), abs(), isdigit(), etc.
In order to use library functions, we usually need to include the header file in which these
library functions are defined.
For instance, in order to use mathematical functions such as sqrt() and abs(), we need to
include the header file cmath.
#include <iostream>
#include <cmath>
int main() {
number = 25.0;
squareRoot = sqrt(number);
cout << "Square root of " << number << " = " << squareRoot;
return 0;
}
Output
Square root of 25 = 5
In this program, the sqrt() library function is used to calculate the square root of a
number.
The function declaration of sqrt() is defined in the cmath header file. That's why we need
to use the code #include <cmath> to use the sqrt() function.
For better understanding of arguments and return in functions, user-defined functions can
be categorised as:
Consider a situation in which you have to check prime number. This problem is solved below
by making user-defined function in 4 different ways as mentioned above.
# include <iostream>
void prime();
int main()
prime();
return 0;
}
// Return type of function is void because value is not returned.
void prime()
if(num % i == 0)
flag = 1;
break;
if (flag == 1)
else
{
cout << num << " is a prime number.";
In the above program, prime() is called from the main() with no arguments.
prime() takes the positive number from the user and checks whether the number is a
prime number or not.
Since, return type of prime() is void, no value is returned from the function.
#include <iostream>
int prime();
int main()
num = prime();
if (num%i == 0)
flag = 1;
break;
}
}
if (flag == 1)
else
return 0;
int prime()
int n;
cin >> n;
return n;
In the above program, prime() function is called from the main() with no arguments.
prime() takes a positive integer from the user. Since, return type of the function is an int,
it returns the inputted number from the user back to the calling main() function.
Then, whether the number is prime or not is checked in the main() itself and printed onto
the screen.
#include <iostream>
int main()
int num;
prime(num);
return 0;
// There is no return value to calling function. Hence, return type of function is void. */
void prime(int n)
int i, flag = 0;
if (n%i == 0)
{
flag = 1;
break;
if (flag == 1)
else {
In the above program, positive number is first asked from the user which is stored in the
variable num.
Then, num is passed to the prime() function where, whether the number is prime or not is
checked and printed.
Since, the return type of prime() is a void, no value is returned from the function.
#include <iostream>
int main()
{
flag = prime(num);
if(flag == 1)
else
return 0;
int prime(int n)
int i;
if(n % i == 0)
return 1;
return 0;
}
Object Oriented Programming is a paradigm that provides many concepts such as inheritance,
data binding, polymorphism etc.
o Object
o Class
o Inheritance
o Polymorphism
o Abstraction
o Encapsulation
Object
Any entity that has state and behavior is known as an object. For example: chair, pen, table,
keyboard, bike etc. It can be physical and logical.
Class
Inheritance
When one object acquires all the properties and behaviours of parent object i.e. known as
inheritance. It provides code reusability. It is used to achieve runtime polymorphism.
Polymorphism
When one task is performed by different ways i.e. known as polymorphism. For example: to
convince the customer differently, to draw something e.g. shape or rectangle etc.
Abstraction
Hiding internal details and showing functionality is known as abstraction. For example: phone
call, we don't know the internal processing.
Encapsulation
Binding (or wrapping) code and data together into a single unit is known as
encapsulation. For example: capsule, it is wrapped with different medicines.
C++ Object
In C++, Object is a real world entity, for example, chair, car, pen, mobile, laptop etc.
In other words, object is an entity that has state and behavior. Here, state means data and
behavior means functionality.
Object is an instance of a class. All the members of the class can be accessed through object.
Let's see an example to create object of student class using s1 as the reference variable.
In this example, Student is the type and s1 is the reference variable that refers to the
instance of Student class.
C++ Class
In C++, object is a group of similar objects. It is a template from which objects are created. It
can have fields, methods, constructors etc.
Let's see an example of C++ class that has three fields only.
1. class Student
2. {
3. public:
4. int id; //field or data member
5. float salary; //field or data member
6. String name;//field or data member
7. }
Write a program to create a class Student having following data members:
1) Name 2)Roll No 3)Percentage for one Student
#include<iostream>
using namespace std;
class Student
{
private:
char name[30];
int rollno;
float per;
public:
void getdata()
{
cout<<"Enter Name:";
cin>>name;
cout<<"Enter RollNo:";
cin>>rollno;
cout<<"Enter Per:";
cin>>per;
}
void putdata()
{
cout<<"Display Student Data:\n";
cout<<"\nName:"<<name;
cout<<"\nRoll no.:"<<rollno;
cout<<"\nPercentage:"<<per;
}
};
int main()
{
Student s1;
s1.getdata();
s1.putdata();
return 0;
}
Write a program to create a class Employee having following data members:
1) Emp_Name 2)Emp_Id 3)Salary for one Employee
#include<iostream>
using namespace std;
class Employee
{
private:
char Emp_Name[30];
int Emp_Id;
float Salary;
public:
void getdata()
{
cout<<”Enter Employee Data”;
cout<<"Enter Employee Name:";
cin>>Emp_Name;
cout<<"Enter Employee Id:";
cin>>Emp_Id;
cout<<"Enter Employee Salary:";
cin>>Salary;
}
void putdata()
{
cout<<"Display Employee Data:\n";
cout<<"\nEmp_Name:"<<Emp_Name;
cout<<"\nEmp_Id:"<<Emp_Id;
cout<<"\nSalary:"<<Salary;
}
};
int main()
{
Employee e1;
e1.getdata();
e1.putdata();
return 0;
}
Write a program to create a class Book having following data members:
1) Book_Name 2)Author3)Price for one Book
#include<iostream>
using namespace std;
class Book
{
private:
char Book_Name[30];
char Author[30];
float Price;
public:
void getdata()
{
cout<<"Enter Book Data\n";
cout<<"Enter Book Name:";
cin>> Book_Name;
cout<<"Enter Author Name :";
cin>>Author;
cout<<"Enter Book Price:";
cin>>Price;
}
void putdata()
{
cout<<"\nDisplay Book Data:\n";
cout<<"\nBook Name:"<<Book_Name;
cout<<"\nAuthor:"<<Author;
cout<<"\nPrice:"<<Price;
}
};
int main()
{
Book b1;
b1.getdata();
b1.putdata();
return 0;
}
Write a program to create a class Student having following data members:
1) Name 2)Roll No 3)Percentage for two Student
#include<iostream>
using namespace std;
class Student
{
private:
char name[30];
int rollno;
float per;
public:
void getdata()
{
cout<<"\nEnter Name:";
cin>>name;
cout<<"Enter RollNo:";
cin>>rollno;
cout<<"Enter Per:";
cin>>per;
}
void display()
{
cout<<"Display Student Data:\n";
cout<<"\nName:"<<name;
cout<<"\nRoll no.:"<<rollno;
cout<<"\nPercentage:\n"<<per;
}
};
int main()
{
Student s1,s2;
s1.getdata();
s1.display();
s2.getdata();
s2.display();
return 0;
}
Write a program to create a class Book having following data members:
1) Book_Name 2)Author3)Price 4)Page No 5)Year for two Book
#include<iostream>
using namespace std;
class Book
{
private:
char Book_Name[30];
char Author[30];
float Price;
int Page_No;
int year;
public:
void getdata()
{
cout<<"Enter Book Data\n";
cout<<"Enter Book Name:";
cin>> Book_Name;
cout<<"Enter Author Name :";
cin>>Author;
cout<<"Enter Book Price:";
cin>>Price;
cout<<"Enter Page No:";
cin>>Page_No;
cout<<"Enter Book Publish Year:";
cin>>year;
}
void putdata()
{
cout<<"\nDisplay Book Data:\n";
cout<<"\nBook Name:"<<Book_Name;
cout<<"\nAuthor:"<<Author;
cout<<"\nPrice:"<<Price;
cout<<"\nPage No:"<<Page_no;
cout<<"\nPublish Year:"<<year;
}
};
int main()
{
Book b1,b2;
b1.getdata();
b1.putdata();
b2.getdata();
b2.putdata();
return 0;
}
#include<iostream>
using namespace std;
class Employee
{
private:
char Emp_Name[30];
int Emp_Id;
float Salary;
public:
void getdata()
{
cout<<”Enter Employee Data”;
cout<<"Enter Employee Name:";
cin>>Emp_Name;
cout<<"Enter Employee Id:";
cin>>Emp_Id;
cout<<"Enter Employee Salary:";
cin>>Salary;
}
void display()
{
cout<<"Display Employee Data:\n";
cout<<"\nEmp_Name:"<<Emp_Name;
cout<<"\nEmp_Id:"<<Emp_Id;
cout<<"\nSalary:"<<Salary;
}
};
int main()
{
Employee e[10];
int i;
for(i=1;i<=10;i++)
{
e[i].getdata();
}
for(i=1;i<=10;i++)
{
e[i].display();
}
Return 0;
}
}
void display()
{
cout<<"\nDisplay Book Data:\n";
cout<<"\nBook Name:"<<Book_Name;
cout<<"\nAuthor:"<<Author;
cout<<"\nPrice:"<<Price;
}
};
int main()
{
Book b[5];
int i;
for(i=1;i<=5;i++)
{
b[i].getdata();
}
for(i=1;i<=5;i++)
{
b[i].display();
}
Return 0;
}
C++ Constructor
A Constructor is a special member function for automatic initialization of an object.
They have same name as class name. There can be any number of overloaded constructor inside
a class provided they have a different sets of parameters.
class user_name
Private:
……………
…………….
protected:
…………….
…………………
public:
………..
…………
};
……….
……………
}
Example:-
class Rectangle
int width,height;
public:
int area(void);
};
Rectangle::Rectangle()
…………..
……………
Types of Constructor
1) Default Constructor
2) Parameterized Constructor
3) Copy Constructor
4) Dynamic Constructor
1) Default Constructor: - A constructor which has no argument is known
as default constructor. It is invoked at the time of creating object.
Syntax:
className( );
#include <iostream>
// declare a class
class Wall {
private:
double length;
public:
// create a constructor
Wall() {
length = 5.5;
};
int main() {
// create an object
Wall wall1;
return 0;
}
Program for default constructor
#include <iostream>
using namespace std;
class construct
{
public:
int a, b;
// Default Constructor
construct()
{
a = 10;
b = 20;
}
};
int main()
{
// Default constructor called automatically
// when the object is created
construct c;
cout << "a: " << c.a << endl
<< "b: " << c.b;
return 0;
}
...
XYZ obj(10, 20);
#include <iostream>
using namespace std;
class Add{
public:
//Parameterized constructor
Add(int num1, int num2) {
cout<<(num1+num2)<<endl;
}
};
int main(void){
#include <iostream>
// declare a class
class Wall {
private:
double length;
double height;
public:
length = len;
height = hgt;
double calculateArea() {
};
int main() {
return 0;
....
#include<iostream>
class copyconstructor
private:
public:
x = x1;
y = y1;
/* Copy constructor */
x = sam.x;
y = sam.y;
}
void display()
cout<<x<<" "<<y<<endl;
};
int main()
obj1.display();
obj2.display();
return 0;
#include <iostream>
class Date
public:
Date()
{
cout<<”\n Default Constructor:”;
day=15;
month=12;
year=2013;
day=d;
month=m;
year=y;
void show()
cout<<”\nDay:”<<day<<”\nMonth:”<<month<<”\nYear:”<<year;
};
int main()
Date d;
d.show();
Date d1(07,12,1996);
d1.show();
#include<iostream>
#include<string.h>
class Sample
char *name;
int length;
public:
Sample( )
length = 0;
}
Sample ( char *s )
length = strlen(s);
strcpy( name , s );
void display( )
cout<<name<<endl;
};
int main( )
S1.display( );
S2.display( );
S3.display( );
return 0;
}
Program for Dynamic constructor
#include<iostream>
#include<cstring>
class String
char *name;
int length;
public :
String ()
length=0;
name=new char[length+1];
length=strlen(s);
void display()
{
std::cout<<name <<"\n";
length=a.length+b.length;
delete name;
strcpy(name,a.name);
strcat(name,b.name);
};
int main()
char *first="C++";
String name1(first),name2("Programming"),name3("Awesome"),s1,s2;
s1.join(name1,name2);
s2.join(s1,name3);
name1.display();
name2.display();
name3.display();
s1.display();
s2.display();
Overloading Constructor
Overloaded constructors must have the same name and different number of
arguments
The constructor is called based on the number and types of the arguments
are passed.
We have to pass the argument while creating objects, otherwise the
constructor cannot understand which constructor will be called.
Example
#include <iostream>
class Rect{
private:
int area;
public:
Rect(){
area = 0;
area = a * b;
void display(){
cout << "The area is: " << area << endl;
};
main(){
Rect r1;
r1.display();
r2.display();
Output
The area is: 0
The area is: 12
public:
simple_interest (float a, float b, float c) {
principle = a;
time =b;
rate = c;
}
void display ( ) {
interest =(principle* rate* time)/100;
cout<<"interest ="<<interest ;
}
};
int main(){
float p,r,t;
cout<<"principle amount, time and rate"<<endl;
cout<<"2000 7.5 2"<<endl;
simple_interest s1(2000,7.5,2);//dynamic initialization
s1.display();
return 0;
}
#include <iostream>
class Student {
private:
int rNo;
float perc;
public:
//constructor
Student(int r, float p)
rNo = r;
perc = p;
void read(void)
{
cout << "Enter roll number: ";
void print(void)
cout << "Percentage: " << perc << "%" << endl;
};
//Main code
int main()
int roll_number;
float percentage;
cout << "After initializing the object, the values are..." << endl;
std.print();
std.read();
std.print();
return 0;
Destructor
A destructor works opposite to constructor; it destructs the objects of classes. It can be
defined only once in a class. Like constructors, it is invoked automatically.
A destructor is defined like constructor. It must have same name as class. But it is
prefixed with a tilde sign (~).
The destructor must have the same name as the class name
with a tilde(~) prefix.
It never takes any arguments and no return value.
It cannot be declared as static volatile and constant
It takes no argument and therefore cannot be overloaded
It should have public access in the class declaration.
Syntax:-
~className();
#include <iostream>
class Employee
public:
Employee()
cout<<"Constructor Invoked"<<endl;
~Employee()
cout<<"Destructor Invoked"<<endl;
};
int main(void)
return 0;
In C++, the class which inherits the members of another class is called derived class and the
class whose members are inherited is called base class. The derived class is the specialized
class for the base class.
Types Of Inheritance
C++ supports five types of inheritance:
o Single inheritance
o Multiple inheritance
o Hierarchical inheritance
o Multilevel inheritance
o Hybrid inheritance
Derived Classes
A Derived class is defined as the class derived from the base class.
Where,
visibility mode: The visibility mode specifies whether the features of the base class are
publicly inherited or privately inherited. It can be public or private.
o When the base class is privately inherited by the derived class, public members of the
base class becomes the private members of the derived class. Therefore, the public
members of the base class are not accessible by the objects of the derived class only
by the member functions of the derived class.
o When the base class is publicly inherited by the derived class, public members of the
base class also become the public members of the derived class. Therefore, the public
members of the base class are accessible by the objects of the derived class as well as
by the member functions of the base class.
#include <iostream>
using namespace std;
class Account {
public:
float salary = 60000;
};
class Programmer: public Account {
public:
float bonus = 5000;
};
int main(void) {
Programmer p1;
cout<<"Salary: "<<p1.salary<<endl;
cout<<"Bonus: "<<p1.bonus<<endl;
return 0;
}
Example:-
#include <iostream>
using namespace std;
class A
{
int a = 4;
int b = 5;
public:
int mul()
{
int c = a*b;
return c;
}
};
class B : private A
{
public:
void display()
{
int result = mul();
std::cout <<"Multiplication of a and b is : "<<result<< std::endl;
}
};
int main()
{
B b;
b.display();
return 0;
}
#include <iostream>
using namespace std;
// base class
class Vehicle
{
public:
Vehicle()
{
cout << "This is a Vehicle" << endl;
}
};
// main function
int main()
{
//creating object of sub class will
//invoke the constructor of base classes
Car obj;
return 0;
}
#include <iostream>
class base {
public:
int m;
void getdata ()
};
public:
int n;
void readdata ()
};
class derive2 : public derive1
private:
int o;
public:
void indata()
void product()
};
int main ()
derive2 p;
p.getdata();
p.readdata();
p.indata();
p.product();
return 0;
#include<iostream>
class student
protected:
int rollno;
public:
void get_no(int);
void put_no(void);
};
void student::get_no(int a)
rollno=a;
void student::put_no()
cout<<"RollNO:"<<rollno<<"\n";
}
class test:public student
protected:
float sub1;
float sub2;
public:
void get_marks(float,float);
void put_marks(void);
};
sub1=x;
sub2=y;
void test::put_marks()
cout<<"Marks in Sub1="<<sub1<<"\n";
cout<<"Marks in sub2="<<sub2<<"\n";
float total;
public:
void display(void);
};
void result::display(void)
total=sub1+sub2;
put_no();
put_marks();
cout<<"Total="<<total<<"\n";
int main()
result S1;
S1.get_no(111);
S1.get_marks(75,89);
S1.display();
return 0;
}
C++ Multiple Inheritance
Multiple inheritance is the process of deriving a new class that inherits the attributes from
two or more classes.
#include <iostream>
class A
protected:
int a;
public:
void get_a(int n)
{
a = n;
};
class B
protected:
int b;
public:
void get_b(int n)
b = n;
};
public:
void display()
};
int main()
C c;
c.get_a(10);
c.get_b(20);
c.display();
return 0;
class Vehicle {
public:
Vehicle()
};
class FourWheeler {
public:
FourWheeler()
};
};
// main function
int main()
Car obj;
return 0;
#include <iostream>
class A
protected:
int a;
public:
void get_a()
{
cin>>a;
};
class B : public A
protected:
int b;
public:
void get_b()
cin>>b;
};
class C
protected:
int c;
public:
void get_c()
cin>>c;
};
protected:
int d;
public:
void mul()
get_a();
get_b();
get_c();
};
int main()
D d;
d.mul();
return 0;
#include <iostream>
class ClassA {
public:
int a;
};
public:
int b;
};
public:
int c;
};
class ClassD : public ClassB, public ClassC {
public:
int d;
};
int main()
ClassD obj;
obj.b = 20;
obj.c = 30;
obj.d = 40;
return 0;
#include<iostream>
#include<conio.h>
class student
protected:
int rollnum;
public:
rollnum=num;
void print_rollnum(void)
{
std::cout<<"Roll number is : "<<rollnum<<"\n";
};
protected:
public:
subject1 = a;
subject2 = b;
subject3 = c;
void print_subjectmarks()
{
};
class sports
protected:
float sport_marks;
public:
sport_marks=marks;
void print_sports_marks(void)
};
private:
float total_marks;
public:
void display_total(void);
};
void overall_result::display_total(void)
total_marks=subject1+subject2+subject3+sport_marks;
print_rollnum();
print_subjectmarks();
print_sports_marks();
int main()
{
overall_result stu;
stu.set_rollnum(40);
stu.set_subjectmark(19.8,34.6,89.7);
stu.set_sports_marks(64.3);
stu.display_total();
overall_result stu2;
stu2.set_rollnum(50);
stu2.set_subjectmark(10.8,54.6,59.7);
stu2.set_sports_marks(94.3);
stu2.display_total();
return 0;
class X
public:
int a, b;
void getdata ()
}
};
class Y : public X
public:
void product()
};
class Z: public X {
public:
void sum()
};
int main()
Y obj1;
Z obj2;
obj1.getdata();
obj1.product();
obj2.getdata();
obj2.sum();
return 0;
Example:-
#include<iostream>
class A
public:
int x,y;
void getdata()
cin>>x>>y;
};
class B:public A
public:
void product()
cout<<"\n Product="<<x*y;
};
class C:public A
public:
void sum()
cout<<"\nSum="<<x+y;
};
class D:public A
public:
void sub()
cout<<"\nSub="<<x-y;
};
int main()
B obj1;
C obj2;
D obj3;
obj1.getdata();
obj1.product();
obj2.getdata();
obj2.sum();
obj3.getdata();
obj3.sub();
return 0;
datatype *variable_name;
Advantages of using Pointers
Here, are pros/benefits of using Pointers
Example 1:
#include <iostream>
using namespace std;
int main() {
int x = 27;
int *ip;
ip = &x;
cout << "Value of x is : ";
cout << x << endl;
cout << "Value of ip is : ";
cout << ip<< endl;
cout << "Value of *ip is : ";
cout << *ip << endl;
return 0;
}
For example:
p = arr;
The above is correct since arr represents the arrays' address. Here is
another example:
p = &arr;
ip = arr;
After the above declaration, ip and arr will be equivalent, and they will
share properties. However, a different address can be assigned to ip, but
we cannot assign anything to arr.
Example 2:
#include <iostream>
using namespace std;
int main() {
int *ip;
int arr[] = { 10, 34, 13, 76, 5, 46 };
ip = arr;
for (int x = 0; x < 6; x++) {
cout << *ip << endl;
ip++;
}
return 0;
}
Example 3:
#include <iostream>
using namespace std;
int main() {
int *ip = NULL;
cout << "Value of ip is: " << ip;
return 0;
}
Example 4:
#include <iostream>
test(&a, &b);
int main()
{
// declare variables
int var1 = 3;
C++ Polymorphism
The term "Polymorphism" is the combination of "poly" + "morphs" which means many
forms. It is a greek word. In object-oriented programming, we use 3 main
concepts: inheritance, encapsulation, and polymorphism.
In the above case, the prototype of display() function is the same in both the base
and derived class. Therefore, the static binding cannot be applied. It would be
great if the appropriate function is selected at the run time. This is known as run
time polymorphism.
o Run time polymorphism: Run time polymorphism is achieved when the object's
method is invoked at the run time instead of compile time. It is achieved by method
overriding which is also known as dynamic binding or late binding.
The function to be invoked is known at the compile The function to be invoked is known at the run
time. time.
It is also known as overloading, early binding and It is also known as overriding, Dynamic binding
static binding. and late binding.
Overloading is a compile time polymorphism where Overriding is a run time polymorphism where
more than one method is having the same name but more than one method is having the same
with the different number of parameters or the name, number of parameters and the type of
type of the parameters. the parameters.
#include <iostream>
using namespace std;
class Animal {
public:
void eat(){
cout<<"Eating...";
}
};
class Dog: public Animal
{
public:
void eat()
{ cout<<"Eating bread...";
}
};
int main(void) {
Dog d = Dog();
d.eat();
return 0;
}
Output:
Eating bread...
C++ Run time Polymorphism Example: By using two
derived class
Let's see another example of run time polymorphism in C++ where we are having
two derived classes.
#include <iostream>
using namespace std;
class Shape { // base class
public:
virtual void draw(){ // virtual function
cout<<"drawing..."<<endl;
}
};
class Rectangle: public Shape // inheriting Shape class.
{
public:
void draw()
{
cout<<"drawing rectangle..."<<endl;
}
};
class Circle: public Shape // inheriting Shape class.
{
public:
void draw()
{
cout<<"drawing circle..."<<endl;
}
};
int main(void) {
Shape *s; // base class pointer.
Shape sh; // base class object.
Rectangle rec;
Circle cir;
s=&sh;
s->draw();
s=&rec;
s->draw();
s=○
s->draw();
}
Output:
drawing...
drawing rectangle...
drawing circle...
#include <iostream>
using namespace std;
class Animal { // base class declaration.
public:
string color = "Black";
};
class Dog: public Animal // inheriting Animal class.
{
public:
string color = "Grey";
};
int main(void) {
Animal d= Dog();
cout<<d.color;
}
o methods,
o constructors, and
o indexed properties
Function Overloading is defined as the process of having two or more function with
the same name, but different in parameters is known as function overloading in C++.
In function overloading, the function is redefined by using either different types of
arguments or a different number of arguments. It is only through these differences
compiler can differentiate between the functions.
Let's see the simple example of function overloading where we are changing number
of arguments of add() method.
#include <iostream>
using namespace std;
class Cal {
public:
static int add(int a,int b){
return a + b;
}
static int add(int a, int b, int c)
{
return a + b + c;
}
};
int main(void) {
Cal C; // class object declaration.
cout<<C.add(10, 20)<<endl;
cout<<C.add(12, 20, 23);
return 0;
}
Output:
30
55
Let's see the simple example when the type of the arguments vary.
#include<iostream>
using namespace std;
int mul(int,int);
float mul(float,int);
Output:
r1 is : 42
r2 is : 0.6
When the compiler is unable to decide which function is to be invoked among the
overloaded function, this situation is known as function overloading.
When the compiler shows the ambiguity error, the compiler does not run the
program.
o Type Conversion:
#include<iostream>
using namespace std;
void fun(int);
void fun(float);
void fun(int i)
{
std::cout << "Value of i is : " <<i<< std::endl;
}
void fun(float j)
{
std::cout << "Value of j is : " <<j<< std::endl;
}
int main()
{
fun(12);
fun(1.2);
return 0;
}
#include<iostream>
using namespace std;
void fun(int);
void fun(int,int);
void fun(int i)
{
std::cout << "Value of i is : " <<i<< std::endl;
}
void fun(int a,int b=9)
{
std::cout << "Value of a is : " <<a<< std::endl;
std::cout << "Value of b is : " <<b<< std::endl;
}
int main()
{
fun(12);
return 0;
}
The above example shows an error "call of overloaded 'fun(int)' is ambiguous". The
fun(int a, int b=9) can be called in two ways: first is by calling the function with one
argument, i.e., fun(12) and another way is calling the function with two arguments,
i.e., fun(4,5). The fun(int i) function is invoked with one argument. Therefore, the
compiler could not be able to select among fun(int i) and fun(int a,int b=9).
o Function with pass by reference
#include <iostream>
using namespace std;
void fun(int);
void fun(int &);
int main()
{
int a=10;
fun(a); // error, which f()?
return 0;
}
void fun(int x)
{
std::cout << "Value of x is : " <<x<< std::endl;
}
void fun(int &b)
{
std::cout << "Value of b is : " <<b<< std::endl;
}
Where the return type is the type of value returned by the function.
Let's see the simple example of operator overloading in C++. In this example, void
operator ++ () operator function is defined (inside Test class).
#include <iostream>
using namespace std;
class Test
{
private:
int num;
public:
Test(): num(8){}
void operator ++() {
num = num+2;
}
void Print() {
cout<<"The Count is: "<<num;
}
};
int main()
{
Test tt;
++tt; // calling of a function "void operator ++()"
tt.Print();
return 0;
}
Output:
The Count is: 10
#include <iostream>
using namespace std;
class A
{
int x;
public:
A(){}
A(int i)
{
x=i;
}
void operator+(A);
void display();
};
void A :: operator+(A a)
{
int m = x+a.x;
cout<<"The result of the addition of two objects is : "<<m;
}
int main()
{
A a1(5);
A a2(4);
a1+a2;
return 0;
}
Output:
#include <iostream>
using namespace std;
class Animal {
public:
void eat(){
cout<<"Eating...";
}
};
class Dog: public Animal
{
public:
void eat()
{
cout<<"Eating bread...";
}
};
int main(void) {
Dog d = Dog();
d.eat();
return 0;
}
Output:
Eating bread...
C++ Enumeration
In this article, you will learn to work with enumeration (enum). Also, you will learn where
enums are commonly used in C++ programming.
By default, spring is 0, summer is 1 and so on. You can change the default value of an enum
element during declaration (if necessary).
enum season
{ spring = 0,
summer = 4,
autumn = 8,
winter = 12
};
When you create an enumerated type, only blueprint for the variable is created. Here's
how you can create variables of enum type.
enum boolean { false, true };
// inside function
Here is another way to declare same check variable using different syntax.
enum boolean
false, true
} check;
#include <iostream>
int main()
week today;
today = Wednesday;
return 0;
Output
Day 4
Example2: Changing Default Value of Enums
#include <iostream>
int main() {
seasons s;
s = summer;
return 0;
Output
Summer = 4
An enum variable takes only one value out of many possible values. Example to demonstrate
it,
#include <iostream>
enum suit {
club = 0,
diamonds = 10,
hearts = 20,
spades = 3
} card;
int main()
card = club;
cout << "Size of enum variable " << sizeof(card) << " bytes.";
return 0;
Output
To catch the exceptions, you place some section of code under exception inspection. The
section of code is placed within the try-catch block.
If an exceptional situation occurs within that section of code, an exception will be thrown.
Next, the exception handler will take over control of the program.
In case no exceptional circumstance occurs, the code will execute normally. The handlers
will be ignored.
throw- when a program encounters a problem, it throws an exception. The throw keyword
helps the program perform the throw.
catch- a program uses an exception handler to catch an exception. It is added to the
section of a program where you need to handle the problem. It's done using the catch
keyword.
try- the try block identifies the code block for which certain exceptions will be activated.
It should be followed by one/more catch blocks.
Suppose a code block will raise an exception. The exception will be caught by a method
using try and catch keywords. The try/catch block should surround code that may throw an
exception. Such code is known as protected code.
Syntax:
try {
// catch block
// catch block
// catch block
Although we have one try statement, we can have many catch statements.
The exception1, exception2, and exceptionN are your defined names for referring to the
exceptions.
Example 1:
#include<iostream>
#include<vector>
using namespace std;
int main() {
vector<int> vec;
vec.push_back(0);
vec.push_back(1);
// access the third element, which doesn't exist
try
{
vec.at(2);
}
catch (exception& ex)
{
cout << "Exception occurred!" << endl;
}
return 0;
}
Output:
Example 2:
#include <iostream>
using namespace std;
double zeroDivision(int x, int y) {
if (y == 0) {
throw "Division by Zero!";
}
return (x / y);
}
int main() {
int a = 11;
int b = 0;
double c = 0;
try {
c = zeroDivision(a, b);
cout << c << endl;
}
catch (const char* message) {
cerr << message << endl;
}
return 0;
}
Example 3:
#include <iostream>
#include <exception>
using namespace std;
int main() {
try {
throw newex;
}
catch (exception& ex) {
cout << ex.what() << '\n';
}
return 0;
}