C Tutorial
C Tutorial
TUTORIALSEXAMPLESREFERENCESONLINE COMPILER
C++ is a powerful general-purpose programming language. It can be used to develop
operating systems, browsers, games, and so on. C++ supports different ways of
programming like procedural, object-oriented, functional, and so on. This makes C++
powerful as well as flexible.
Our C++ programming tutorial will guide you to learn C++ programming one step at a time.
Page Index
• C++ Introduction
• C++ Flow Control
• C++ Functions
• C++ Arrays & String
• C++ Structures
• C++ Object & Class
• C++ Pointers
• C++ Inheritance
• About C++ Programming
• Why learn C++ ?
• How to learn C++ ?
• C++ Resources
C++ Introduction
• C++ if...else
• C++ for Loop
• C++ do...while Loop
• C++ break Statement
• C++ continue Statement
• C++ switch Statement
• C++ goto Statement
C++ Functions
• C++ Functions
• C++ Function Types
• C++ Function Overloading
• C++ Default Argument
• C++ Storage Class
• C++ Recursion
• C++ Return Reference
C++ Arrays & String
• C++ Arrays
• Multidimensional Arrays
• C++ Function and Array
• C++ String
C++ Structures
• C++ Structure
• Structure and Function
• C++ Pointers to Structure
• C++ Enumeration
C++ Object & Class
• C++ Pointer
• C++ Pointers and Arrays
• C++ Pointers and Functions
• C++ Memory Management
C++ Inheritance
• C++ Inheritance
• Inheritance Access Control
• C++ Function Overriding
• Multiple & Multilevel Inheritance
• C++ Friend Function
• C++ Virtual Function
• C++ Templates
C++ Resources
• C++ Examples
• C++ References
• C++ Guide
C++ Output
In C++, cout sends formatted output to standard output devices, such as the
screen. We use the cout object along with the << operator for displaying output.
#include <iostream>
using namespace std;
int main() {
// prints the string enclosed in double quotes
cout << "This is C++ Programming";
return 0;
}
Output
#include <iostream>
int main() {
// prints the string enclosed in double quotes
std::cout << "This is C++ Programming";
return 0;
}
#include <iostream>
using namespace std;
int main() {
int num1 = 70;
double num2 = 256.783;
char ch = 'A';
Output
70
256.783
character: A
Notes:
• The endl manipulator is used to insert a new line. That's why each output
is displayed in a new line.
• The << operator can be used more than once if we want to print different
variables, strings and so on in a single statement. For example:
C++ Input
In C++, cin takes formatted input from standard input devices such as the
keyboard. We use the cin object along with the >> operator for taking input.
Example 3: Integer Input/Output
#include <iostream>
using namespace std;
int main() {
int num;
cout << "Enter an integer: ";
cin >> num; // Taking input
cout << "The number is: " << num;
return 0;
}
Output
Enter an integer: 70
The number is: 70
to take input from the user. The input is stored in the variable num . We use
the >> operator with cin to take input.
Note: If we don't include the using namespace std; statement, we need to
use std::cin instead of cin .
#include <iostream>
using namespace std;
int main() {
char a;
int num;
return 0;
}
Output
Previous Tutorial:
Next Tutorial:
C++ allows us to convert data of one type to that of another. This is known as
type conversion.
1. Implicit Conversion
#include <iostream>
using namespace std;
int main() {
// assigning an int value to num_int
int num_int = 9;
// implicit conversion
// assigning int value to a double variable
num_double = num_int;
return 0;
}
Output
num_int = 9
num_double = 9
num_double = num_int;
Here, the int value is automatically converted to double by the compiler before
it is assigned to the num_double variable. This is an example of implicit type
conversion.
#include <iostream>
using namespace std;
int main() {
int num_int;
double num_double = 9.99;
// implicit conversion
// assigning a double value to an int variable
num_int = num_double;
return 0;
}
Output
num_int = 9
num_double = 9.99
Here, the double value is automatically converted to int by the compiler before
it is assigned to the num_int variable. This is also an example of implicit type
conversion.
Note: Since int cannot have a decimal part, the digits after the decimal point
are truncated in the above example.
As we have seen from the above example, conversion from one data type to
another is prone to data loss. This happens when data of a larger type is
converted to data of a smaller type.
Possible Data Loss During Type
Conversion
(data_type)expression;
For example,
Function-style Casting
We can also use the function like notation to cast data from one type to another.
For example,
#include <iostream>
int main() {
// initializing a double variable
double num_double = 3.56;
cout << "num_double = " << num_double << endl;
return 0;
}
Output
num_double = 3.56
num_int1 = 3
num_int2 = 3
We used both the C style type conversion and the function-style casting for
type conversion and displayed the results. Since they perform the same task,
both give us the same output.
Besides these two type castings, C++ also has four operators for type
conversion. They are known as type conversion operators. They are:
• static_cast
• dynamic_cast
• const_cast
• reinterpret_cast
Recommended Tutorials:
• C++ string to int and Vice-versa
• C++ string to float, double and Vice-versa
Previous Tutorial:
Next Tutorial:
C++ Operators
C++ Operators
In this tutorial, we will learn about the different types of operators in C++ with
the help of examples. In programming, an operator is a symbol that operates on
a value or a variable.
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.
Operators in C++ can be classified into 6 types:
1. Arithmetic Operators
2. Assignment Operators
3. Relational Operators
4. Logical Operators
5. Bitwise Operators
6. Other Operators
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
#include <iostream>
using namespace std;
int main() {
int a, b;
a = 7;
b = 2;
return 0;
}
Output
a + b = 9
a - b = 5
a * b = 14
a / b = 3
a % b = 1
In C++,
7/2 is 3
7.0 / 2 is 3.5
7 / 2.0 is 3.5
% Modulo Operator
The modulo operator % computes the remainder. When a = 9 is divided by b =
4 , the remainder is 1.
int num = 5;
// increasing num by 1
++num;
Here, the value of num gets increased to 6 from its initial value of 5.
Example 2: Increment and Decrement Operators
#include <iostream>
using namespace std;
int main() {
int a = 10, b = 100, result_a, result_b;
return 0;
}
Output
result_a = 11
result_b = 99
In the above program, we used ++ and -- operator as prefixes. We can also use
these operators as postfix.
There is a slight difference when these operators are used as a prefix versus
when they are used as a postfix.
To learn more about these operators, visit increment and decrement operators.
// 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;
#include <iostream>
using namespace std;
int main() {
int a, b, temp;
// 2 is assigned to a
a = 2;
// 7 is assigned to b
b = 7;
return 0;
}
Output
temp = 2
a = 9
#include <iostream>
using namespace std;
int main() {
int a, b;
a = 3;
b = 5;
bool result;
return 0;
}
Output
3 == 5 is 0
3 != 5 is 1
3 > 5 is 0
3 < 5 is 1
3 >= 5 is 0
3 <= 5 is 1
Logical AND.
&& expression1 && expression2
True only if all the operands are true.
Logical OR.
|| expression1 || expression2
True if at least one of the operands is true
Logical NOT.
! !expression
True only if the operand is false.
Suppose,
a = 5
b = 8
Then,
#include <iostream>
using namespace std;
int main() {
bool result;
return 0;
}
Output
(3 != 5) && (3 < 5) is 1
(3 == 5) && (3 < 5) is 0
(3 == 5) && (3 > 5) is 0
(3 != 5) || (3 < 5) is 1
(3 != 5) || (3 > 5) is 1
(3 == 5) || (3 < 5) is 0
!(5 == 2) is 1
!(5 == 5) is 0
5) is 0 (false).
• (3 == 5) && (3 > 5) evaluates to 0 because both operands (3 ==
5) is 1 (true).
• (3 == 5) || (3 > 5) evaluates to 0 because both operands (3 ==
| Binary OR
^ Binary XOR
~ Binary One's Complement
Apart from the operators discussed above, there are a few other operators, such
as sizeof , ? , . , & , etc., that cannot be neatly classified into one or another type.
We will learn more about these operators in later tutorials.
Previous Tutorial:
Next Tutorial:
C++ Comments
In C++, both float and double data types are used for floating-point values.
Floating-point numbers are used for decimal and exponential values. For
example,
We must add the suffix f or F at the end of a float value. This is because the
compiler interprets decimal values without the suffix as double .
Consider this code.
float a = 5.6;
Precision: In general, 7 decimal digits precision Precision: In general, 15 decimal digits prec
Note: Unless you have a specific requirement, always use double instead
of float , as float variables may be prone to introduce errors when working with
large numbers.
int main() {
// Creating a double type variable
double a = 3.912348239293;
return 0;
}
Output
Note: The compiler used for this example (MinGW compiler) allowed for 6 digits.
So, our variable values were rounded off and truncated to 6 digits by the
compiler.
#include <iomanip>
#include <iostream>
int main() {
// Creating a double type variable
double a = 3.912348239293;
return 0;
}
Output
As we can see from the example above, we have specified the precision up to 13
digits.
#include <iomanip>
#include <iostream>
int main() {
// Creating a double type variable
double a = 3.912348239293;
return 0;
}
Output
From the program above, we can see that we have set two different precision
values for float and double .
In both cases, the precision is smaller than the actual digits of the number. So
the last digit is rounded off and the rest is truncated.
Note: If we specify the precision greater than the precision of the data type itself
(7 for float and 15 for double ), then the compiler will give us garbage values
after the precision limit has been exceeded, as can be seen with
the float output in example 2.
C++ outputs exponential numbers and very large numbers in a format called
the scientific format. The variable ex will be outputted in this format by default
since it is a very large number.
In order to force C++ to display our floating-point numbers in
the scientific format regardless of the size of the number, we use the format
specifier scientific inside of cout .
#include <iomanip>
#include <iostream>
int main() {
// Creating a decimal double type variable
double a = 3.912348239293;
long double
Apart from float and double , there is another data type that can store floating-
point numbers. This is known as long double .
Note: The floating-point data types supported by C++ are float , double and long
double . There is no long float .
Share on:
switch (expression) {
case constant1:
// code to be executed if
// expression is equal to constant1;
break;
case constant2:
// code to be executed if
// expression is equal to constant2;
break;
.
.
.
default:
// code to be executed if
// expression doesn't match any constant
}
Flowchart
of C++ switch...case statement
Example: Create a Calculator using the switch Statement
int main() {
char oper;
float num1, num2;
cout << "Enter an operator (+, -, *, /): ";
cin >> oper;
cout << "Enter two numbers: " << endl;
cin >> num1 >> num2;
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:
// operator is doesn't match any case constant (+, -, *, /)
cout << "Error! The operator is not correct";
break;
}
return 0;
}
Output 1
Output 2
Enter an operator (+, -, *, /): -
Enter two numbers:
2.3
4.5
2.3 - 4.5 = -2.2
Output 3
Output 4
Output 5
Notice that the break statement is used inside each case block. This terminates
the switch statement.
If the break statement is not used, all cases after the correct case are executed.
Previous Tutorial:
C++ continue
Next Tutorial:
C++ if Statement
The syntax of the if statement is:
if (condition) {
// body of if statement
}
Working of
C++ if Statement
#include <iostream>
using namespace std;
int main() {
int number;
Output 1
Enter an integer: 5
You entered a positive number: 5
This statement is always executed.
When the user enters 5 , the condition number > 0 is evaluated to true and the
statement inside the body of if is executed.
Output 2
Enter a number: -5
This statement is always executed.
When the user enters -5 , the condition number > 0 is evaluated to false and the
statement inside the body of if is not executed.
C++ if...else
The if statement can have an optional else clause. Its syntax is:
if (condition) {
// block of code if condition is true
}
else {
// block of code if condition is false
}
int main() {
int number;
Output 1
Enter an integer: 4
You entered a positive integer: 4.
This line is always printed.
In the above program, we have the condition number >= 0 . If we enter the
Enter an integer: -4
You entered a negative integer: -4.
This line is always printed.
Here, we enter -4 . So, the condition is false . Hence, the statement inside the
body of else is executed.
if (condition1) {
// code block 1
}
else if (condition2){
// code block 2
}
else {
// code block 3
}
Here,
#include <iostream>
using namespace std;
int main() {
int number;
Output 1
Enter an integer: 1
You entered a positive integer: 1.
This line is always printed.
Output 2
Enter an integer: -2
You entered a negative integer: -2.
This line is always printed.
Output 3
Enter an integer: 0
You entered 0.
This line is always printed.
In this program, we take a number from the user. We then use the if...else
if...else ladder to check whether the number is positive, negative, or zero.
If the number is greater than 0 , the code inside the if block is executed. If the
number is less than 0 , the code inside the else if block is executed. Otherwise,
the code inside the else block is executed.
// outer if statement
if (condition1) {
// statements
// inner if statement
if (condition2) {
// statements
}
}
Notes:
• We can add else and else if statements to the inner if statement as
required.
• The inner if statement can also be inserted inside the outer else or else
if statements (if they exist).
• We can nest multiple layers of if statements.
Example 4: C++ Nested if
#include <iostream>
using namespace std;
int main() {
int num;
// outer if condition
if (num != 0) {
// inner if condition
if ((num % 2) == 0) {
cout << "The number is even." << endl;
}
// inner else condition
else {
cout << "The number is odd." << endl;
}
}
// outer else condition
else {
cout << "The number is 0 and it is neither even nor odd." << endl;
}
cout << "This line is always printed." << endl;
}
Output 1
Enter an integer: 34
The number is even.
This line is always printed.
Output 2
Enter an integer: 35
The number is odd.
This line is always printed.
Output 3
Enter an integer: 0
The number is 0 and it is neither even nor odd.
This line is always printed.
int number = 5;
if (number > 0) {
cout << "The number is positive." << endl;
}
else {
cout << "The number is negative." << endl;
}
with
int number = 5;
if (number > 0)
cout << "The number is positive." << endl;
else
cout << "The number is negative." << endl;
Note: Although it's not necessary to use { } if the body of if...else has only
one statement, using { } makes your code more readable.
Previous Tutorial:
C++ Comments
Next Tutorial:
For example, let's say we want to show a message 100 times. Then instead of
writing the print statement 100 times, we can use a loop.
That was just a simple example; we can achieve much more efficiency and
sophistication in our programs by making effective use of loops.
• for loop
• while loop
• do...while loop
This tutorial focuses on C++ for loop. We will learn about the other type of loops
in the upcoming tutorials.
Here,
#include <iostream>
int main() {
for (int i = 1; i <= 5; ++i) {
cout << i << " ";
}
return 0;
}
Output
1 2 3 4 5
#include <iostream>
int main() {
for (int i = 1; i <= 5; ++i) {
cout << "Hello World! " << endl;
}
return 0;
}
Output
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
#include <iostream>
int main() {
int num, sum;
sum = 0;
return 0;
}
Output
In the above example, we have two variables num and sum . The sum variable is
assigned with 0 and the num variable is assigned with the value provided by the
user.
Note that we have used a for loop.
Here,
+ ... + 10 .
Here, for every value in the collection , the for loop is executed and the value is
assigned to the variable .
#include <iostream>
int main() {
return 0;
}
Output
1 2 3 4 5 6 7 8 9 10
If the condition in a for loop is always true , it runs forever (until memory is full).
For example,
// infinite for loop
for(int i = 1; i > 0; i++) {
// block of code
}
In the above program, the condition is always true which will then run the code
for infinite times.
In the next tutorial, we will learn about while and do...while loop.
Previous Tutorial:
C++ if...else
Next Tutorial:
That was just a simple example; we can achieve much more efficiency and
sophistication in our programs by making effective use of loops.
while (condition) {
// body of the loop
}
Here,
#include <iostream>
int main() {
int i = 1;
Output
1 2 3 4 5
#include <iostream>
using namespace std;
int main() {
int number;
int sum = 0;
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
In this program, the user is prompted to enter a number, which is stored in the
variable number .
In order to store the sum of the numbers, we declare a variable sum and initialize
it to the value of 0 .
The while loop continues until the user enters a negative number. During each
iteration, the number entered by the user is added to the sum variable.
When the user enters a negative number, the loop terminates. Finally, the total
sum is displayed.
do {
// body of loop;
}
while (condition);
Here,
• The body of the loop is executed at first. Then the condition is evaluated.
• If the condition evaluates to true , the body of the loop inside
the do statement is executed again.
• The condition is evaluated once again.
• If the condition evaluates to true , the body of the loop inside
the do statement is executed again.
• This process continues until the condition evaluates to false . Then the
loop stops.
#include <iostream>
int main() {
int i = 1;
Output
1 2 3 4 5
#include <iostream>
using namespace std;
int main() {
int number = 0;
int sum = 0;
do {
sum += number;
// take input from the user
cout << "Enter a number: ";
cin >> number;
}
while (number >= 0);
return 0;
}
Output 1
Enter a number: 6
Enter a number: 12
Enter a number: 7
Enter a number: 0
Enter a number: -2
The sum is 25
Here, the do...while loop continues until the user enters a negative number.
When the number is negative, the loop terminates; the negative number is not
added to the sum variable.
Output 2
Enter a number: -6
The sum is 0.
The body of the do...while loop runs only once if the user enters a negative
number.
int count = 1;
do {
// body of loop
}
while(count == 1);
In the above programs, the condition is always true . Hence, the loop body will
run for infinite times.
However, while and do...while loops are usually used when the number of
iterations is unknown. For example,
while (condition) {
// body of the loop
}
Check out these examples to learn more:
Previous Tutorial:
Next Tutorial:
C++ break
break;
Before you learn about the break statement, make sure you know about:
• C++ for loop
• C++ if...else
• C++ while loop
#include <iostream>
using namespace std;
int main() {
for (int i = 1; i <= 5; i++) {
// break condition
if (i == 3) {
break;
}
cout << i << endl;
}
return 0;
}
Output
1
2
In the above program, the for loop is used to print the value of i in each
iteration. Here, notice the code:
if (i == 3) {
break;
}
This means, when i is equal to 3, the break statement terminates the loop.
Hence, the output doesn't include values greater than or equal to 3.
Note: The break statement is usually used with decision-making statements.
#include <iostream>
using namespace std;
int main() {
int number;
int sum = 0;
while (true) {
// take input from the user
cout << "Enter a number: ";
cin >> number;
// break condition
if (number < 0) {
break;
}
return 0;
}
Output
Enter a number: 1
Enter a number: 2
Enter a number: 3
Enter a number: -5
The sum is 6.
In the above program, the user enters a number. The while loop is used to print
the total sum of numbers entered by the user. Here, notice the code,
if(number < 0) {
break;
}
This means, when the user enters a negative number, the break statement
terminates the loop and codes outside the loop are executed.
The while loop continues until the user enters a negative number.
#include <iostream>
using namespace std;
int main() {
int number;
int sum = 0;
// first loop
for (int i = 1; i <= 3; i++) {
// second loop
for (int j = 1; j <= 3; j++) {
if (i == 2) {
break;
}
cout << "i = " << i << ", j = " << j << endl;
}
}
return 0;
}
Output
i = 1, j = 1
i = 1, j = 2
i = 1, j = 3
i = 3, j = 1
i = 3, j = 2
i = 3, j = 3
terminates the inner loop, and the control flow of the program moves to the
outer loop.
Hence, the value of i = 2 is never displayed in the output.
The break statement is also used with the switch statement. To learn more,
visit C++ switch statement.
Previous Tutorial:
Next Tutorial:
C++ continue
continue;
Before you learn about the continue statement, make sure you know about,
#include <iostream>
using namespace std;
int main() {
for (int i = 1; i <= 5; i++) {
// condition to continue
if (i == 3) {
continue;
}
return 0;
}
Output
1
2
4
5
In the above program, we have used the the for loop to print the value of i in
each iteration. Here, notice the code,
if (i == 3) {
continue;
}
This means
• When i is equal to 3 , the continue statement skips the current iteration
and starts the next iteration
• Then, i becomes 4 , and the condition is evaluated again.
• Hence, 4 and 5 are printed in the next two iterations.
Note: The continue statement is almost always used with decision-making
statements.
#include <iostream>
using namespace std;
int main() {
int sum = 0;
int number = 0;
// continue condition
if (number > 50) {
cout << "The number is greater than 50 and won't be calculated."
<< endl;
number = 0; // the value of number is made 0 again
continue;
}
}
return 0;
}
Output
Enter a number: 12
Enter a number: 0
Enter a number: 2
Enter a number: 30
Enter a number: 50
Enter a number: 56
The number is greater than 50 and won't be calculated.
Enter a number: 5
Enter a number: -3
The sum is 99
In the above program, the user enters a number. The while loop is used to print
the total sum of positive numbers entered by the user, as long as the numbers
entered are not greater than 50 .
Notice the use of the continue statement.
• When the user enters a number greater than 50 , the continue statement
skips the current iteration. Then the control flow of the program goes to
the condition of while loop.
• When the user enters a number less than 0 , the loop terminates.
Note: The continue statement works in the same way for the do...while loops.
continue with Nested loop
When continue is used with nested loops, it skips the current iteration of the
inner loop. For example,
#include <iostream>
using namespace std;
int main() {
int number;
int sum = 0;
// first loop
for (int i = 1; i <= 3; i++) {
// second loop
for (int j = 1; j <= 3; j++) {
if (j == 2) {
continue;
}
cout << "i = " << i << ", j = " << j << endl;
}
}
return 0;
}
Output
i = 1, j = 1
i = 1, j = 3
i = 2, j = 1
i = 2, j = 3
i = 3, j = 1
i = 3, j = 3
In the above program, when the continue statement executes, it skips the
current iteration in the inner loop. And the control of the program moves to
the update expression of the inner loop.
Hence, the value of j = 2 is never displayed in the output.
Note: The break statement terminates the loop entirely. However,
the continue statement only skips the current iteration.
Previous Tutorial:
C++ break
Next Tutorial:
switch (expression) {
case constant1:
// code to be executed if
// expression is equal to constant1;
break;
case constant2:
// code to be executed if
// expression is equal to constant2;
break;
.
.
.
default:
// code to be executed if
// expression doesn't match any constant
}
int main() {
char oper;
float num1, num2;
cout << "Enter an operator (+, -, *, /): ";
cin >> oper;
cout << "Enter two numbers: " << endl;
cin >> num1 >> num2;
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:
// operator is doesn't match any case constant (+, -, *, /)
cout << "Error! The operator is not correct";
break;
}
return 0;
}
Output 1
Output 2
Output 3
Output 4
Output 5
Notice that the break statement is used inside each case block. This terminates
the switch statement.
If the break statement is not used, all cases after the correct case are executed.
Previous Tutorial:
C++ continue
Next Tutorial:
In C++ programming, goto statement is used for altering the normal sequence of
program execution by transferring control to some other part of the program.
goto label;
... .. ...
... .. ...
... .. ...
label:
statement;
... .. ...
In the syntax above, label is an identifier. When goto label; is encountered, the
control of program jumps to label: and executes the code below it.
# include <iostream>
using namespace std;
int main()
{
float num, average, sum = 0.0;
int i, n;
jump:
average = sum / (i - 1);
cout << "\nAverage = " << average;
return 0;
}
Output
Average = 3.95
You can write any C++ program without the use of goto statement and is
generally considered a good idea not to use them.
Reason to Avoid goto Statement
The goto statement gives the power to jump to any part of a program but,
makes the logic of the program complex and tangled.
The goto statement can be replaced in most of C++ program with the use
of break and continue statements.
In C++, data types are declarations for variables. This determines the type and
size of data associated with variables. For example,
int Integer 2 or 4
float Floating-point 4
char Character 1
bool Boolean 1
void Empty 0
1. C++ int
• float and double are used to store floating-point numbers (decimals and
exponentials).
• The size of float is 4 bytes and the size of double is 8 bytes.
Hence, double has two times the precision of float . To learn more, visit
C++ float and double.
• For example,
As mentioned above, these two data types are also used for exponentials. For
example,
3. C++ char
Note: In C++, an integer value is stored in a char variable rather than the
character itself. To learn more, visit C++ characters.
4. C++ wchar_t
• Wide character wchar_t is similar to the char data type, except its size is 2
bytes instead of 1.
• It is used to represent characters that require more memory to represent
them than a single char .
• For example,
5. C++ bool
• The bool data type has one of two possible values: true or false .
• Booleans are used in conditional statements and loops (which we will
learn in later chapters).
• For example,
bool cond = false;
6. C++ void
1. signed
2. unsigned
3. short
4. long
We can modify the following data types with the above modifiers:
• int
• double
• char
C++ Modified Data Types List
Size (in
Data Type Meaning
Bytes)
long long 8 used for very large integers (equivalent to long long int
long b = 4523232;
long int c = 2345342;
long double d = 233434.56343;
short d = 3434233; // Error! out of range
unsigned int a = -5; // Error! can only store positive numbers or 0
Previous Tutorial:
Next Tutorial:
C++ Functions
In this tutorial, we will learn about the C++ function and function expressions
with the help of examples.
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 declaration
void greet() {
cout << "Hello World";
}
Here,
• the name of the function is greet()
• the return type of the function is void
• the empty parentheses mean it doesn't have any parameters
Calling a Function
int main() {
// calling a function
greet();
#include <iostream>
using namespace std;
// declaring a function
void greet() {
cout << "Hello there!";
}
int main() {
return 0;
}
Output
Hello there!
Function Parameters
return 0;
}
#include <iostream>
using namespace std;
// display a number
void displayNum(int n1, float n2) {
cout << "The int number is " << n1;
cout << "The double number is " << n2;
}
int main() {
int num1 = 5;
double num2 = 5.5;
return 0;
}
Output
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,
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
int add(int a, int b) {
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
void add(int, int);
int main() {
// calling the function before declaration.
add(5, 3);
return 0;
}
// function definition
void add(int a, int b) {
cout << (a + b);
}
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 add(int, int);
int main() {
int sum;
return 0;
}
// function definition
int add(int a, int b) {
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.
That's why we have used a function prototype in this example.
• 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>
using namespace std;
int main() {
double number, squareRoot;
number = 25.0;
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.
To learn more, visit C++ Standard Library functions.
void prime();
int main()
{
// No argument is passed to prime()
prime();
return 0;
}
if (flag == 1)
{
cout << num << " is not a prime number.";
}
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.
Example 2: No arguments passed but a return value
#include <iostream>
using namespace std;
int prime();
int main()
{
int num, i, flag = 0;
if (flag == 1)
{
cout<<num<<" is not a prime number.";
}
else
{
cout<<num<<" is a prime number.";
}
return 0;
}
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.
int main()
{
int num;
cout << "Enter a positive integer to check: ";
cin >> num;
if (flag == 1)
{
cout << n << " is not a prime number.";
}
else {
cout << n << " is a prime number.";
}
}
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.
int main()
{
int num, flag = 0;
cout << "Enter positive integer to check: ";
cin >> num;
if(flag == 1)
cout << num << " is not a prime number.";
else
cout<< num << " is a prime number.";
return 0;
}
/* This function returns integer value. */
int prime(int n)
{
int i;
for(i = 2; i <= n/2; ++i)
{
if(n % i == 0)
return 1;
}
return 0;
}
In the above program, a positive integer is asked from the user and stored in the
variable num .
Then, num is passed to the function prime() where, whether the number is prime
or not is checked.
Since, the return type of prime() is an int , 1 or 0 is returned to the main() calling
function. If the number is a prime number, 1 is returned. If not, 0 is returned.
Back in the main() function, the returned 1 or 0 is stored in the variable flag , and
the corresponding text is printed onto the screen.
The particular method is chosen depending upon the situation and how you
want to solve a problem.
In C++, two functions can have the same name if the number and/or type of
arguments passed is different.
These functions having the same name but different arguments are known as
overloaded functions. For example:
Notice that the return types of all these 4 functions are not the same.
Overloaded functions may or may not have different return types but they must
have different arguments. For example,
// Error code
int test(int a) { }
double test(int b){ }
Here, both functions have the same name, the same type, and the same number
of arguments. Hence, the compiler will throw an error.
int main() {
Output
Absolute value of -5 = 5
Absolute value of 5.5 = 5.5
Working of
overloading for the absolute() function
In this program, we overload the absolute() function. Based on the type of
parameter passed during the function call, the corresponding function is called.
#include <iostream>
using namespace std;
int main() {
int a = 5;
double b = 5.5;
return 0;
}
Output
Integer number: 5
Float number: 5.5
Integer number: 5 and double number: 5.5
Here, the display() function is called three times with different arguments.
Depending on the number and type of arguments passed, the
corresponding display() function is called.
Working of
overloading for the display() function
The return type of all these functions is the same but that need not be the case
for function overloading.
Note: In C++, many standard library functions are overloaded. For example,
the sqrt() function can take double , float , int, etc. as parameters. This is
possible because the sqrt() function is overloaded in C++.
However, if arguments are passed while calling the function, the default
arguments are ignored.
1. When temp() is called, both the default parameters are used by the
function.
2. When temp(6) is called, the first argument becomes 6 while the default
value is used for the second parameter.
3. When temp(6, -2.3) is called, both the default parameters are overridden,
resulting in i = 6 and f = -2.3 .
#include <iostream>
using namespace std;
int main() {
int count = 5;
return 0;
}
Output
No argument passed: ***
First argument passed: ###
Both arguments passed: $$$$$
2. display('#') is called with only one argument. In this case, the first
becomes '#' . The second default parameter n = 1 is retained.
3. display('#', count) is called with both arguments. In this case, default
arguments are not used.
We can also define the default parameters in the function definition itself. The
program below is equivalent to the one above.
#include <iostream>
using namespace std;
int main() {
int count = 5;
Things to Remember
1. Once we provide a default value for a parameter, all subsequent
parameters must also have default values. For example,
2. // Invalid
3. void add(int a, int b = 3, int c, int d);
4.
5. // Invalid
6. void add(int a, int b = 3, int c, int d = 4);
7.
8. // Valid
}
Previous Tutorial:
Every variable in C++ has two features: type and storage class.
Type specifies the type of data that can be stored in a variable. For
example: int , float , char etc.
And, storage class controls two different properties of a variable: lifetime
(determines how long a variable can exist) and scope (determines which part of
the program can access it).
Depending upon the storage class of a variable, it can be divided into 4 major
types:
• Local variable
• Global variable
• Static local variable
• Register Variable
• Thread Local Storage
Local Variable
A variable defined inside a function (defined inside function body between
braces) is called a local variable or automatic variable.
Its scope is only limited to the function where it is defined. In simple terms, local
variable exists and can be accessed only inside a function.
The life of a local variable ends (It is destroyed) when the function exits.
#include <iostream>
using namespace std;
void test();
int main()
{
// local variable to main()
int var = 5;
test();
void test()
{
// local variable to test()
int var1;
var1 = 6;
The variable var cannot be used inside test() and var1 cannot be used
inside main() function.
Keyword auto was also used for defining local variables before as: auto int var;
But, after C++11 auto has a different meaning and should not be used for
defining local variables.
Global Variable
If a variable is defined outside all functions, then it is called a global variable.
The scope of a global variable is the whole program. This means, It can be used
and changed at any part of the program after its declaration.
#include <iostream>
using namespace std;
void test();
int main()
{
++c;
// Outputs 13
cout << c <<endl;
test();
return 0;
}
void test()
{
++c;
// Outputs 14
cout << c;
}
Output
13
14
... .. ...
int main()
static float a;
... .. ...
A static local variable exists only inside a function where it is declared (similar to
a local variable) but its lifetime starts when the function is called and ends only
when the program ends.
The main difference between local variable and static variable is that, the value
of static variable persists the end of the program.
#include <iostream>
using namespace std;
void test()
{
// var is a static variable
static int var = 0;
++var;
int main()
{
test();
test();
return 0;
}
Output
1
2
1
1
However, this keyword was deprecated in C++11 and should not be used.
C++ Recursion
In this tutorial, we will learn about recursive function in C++ and its working with
the help of examples.
A function that calls itself is known as a recursive function. And, this technique is
known as recursion.
void recurse()
{
... .. ...
recurse();
... .. ...
}
int main()
{
... .. ...
recurse();
... .. ...
}
The figure below shows how recursion works by calling itself over and over
again.
// Factorial of n = 1*2*3*...*n
#include <iostream>
using namespace std;
int factorial(int);
int main() {
int n, result;
result = factorial(n);
cout << "Factorial of " << n << " = " << result;
return 0;
}
int factorial(int n) {
if (n > 1) {
return n * factorial(n - 1);
} else {
return 1;
}
}
Output
In C++ Programming, not only can you pass values by reference to a function but
you can also return a value by reference.
To understand this feature, you should have the knowledge of:
• Global variables
Example: Return by Reference
#include <iostream>
using namespace std;
// Global variable
int num;
// Function declaration
int& test();
int main()
{
test() = 5;
return 0;
}
int& test()
{
return num;
}
Output
In program above, the return type of function test() is int& . Hence, this function
returns a reference of the variable num .
The return statement is return num; . Unlike return by value, this statement
doesn't return value of num , instead it returns the variable itself (address).
So, when the variable is returned, it can be assigned a value as done in test() =
5;
This stores 5 to the variable num , which is displayed onto the screen.
Important Things to Remember When Returning by Reference.
• Ordinary function returns value but this function doesn't. Hence, you
cannot return a constant from the function.
• int& test() {
• return 2;
• int& test()
• {
• int n = 2;
• return n;
C++ Arrays
In this tutorial, we will learn to work with arrays. We will learn to declare,
initialize, and access array elements in C++ programming with the help of
examples.
In C++, an array is a variable that can store multiple values of the same type. For
example,
Suppose a class has 27 students, and we need to store the grades of all of them.
Instead of creating 27 separate variables, we can simply create an array:
double grade[27];
Here, grade is an array that can hold a maximum of 27 elements of double type.
In C++, the size and type of arrays cannot be changed after its declaration.
dataType arrayName[arraySize];
For example,
int x[6];
Here,
Elements of
an array in C++
Few Things to Remember:
• 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.
In C++, if an array has a size n , we can store upto n number of elements in the
array. However, what will happen if we store less than n number of elements.
For example,
Here, the array x has a size of 6 . However, we have initialized it with only 3
elements.
In such cases, the compiler assigns random values to the remaining places.
Oftentimes, this random value is simply 0 .
Empty array
members are automatically assigned the value 0
int main() {
int numbers[5] = {7, 5, 6, 12, 35};
return 0;
}
Output
#include <iostream>
using namespace std;
int main() {
int numbers[5];
return 0;
}
Output
Enter 5 numbers:
11
12
13
14
15
The numbers are: 11 12 13 14 15
#include <iostream>
using namespace std;
int main() {
double sum = 0;
double count = 0;
double average;
return 0;
}
Output
In this program:
2. Then we used a range based for loop to print the array elements. In each
iteration of the loop, we add the current array element to sum .
3. We also increase the value of count by 1 in each iteration, so that we can
get the size of the array by the end of the for loop.
4. After printing all the elements, we print the sum and the average of all the
numbers. The average of the numbers is given by average = sum / count;
However, if we try to access the element at index 10 or more than 10, it will
result in Undefined Behaviour.
Previous Tutorial:
Next Tutorial:
Multidimensional Arrays
int x[3][4];
float x[2][4][3];
2 x 4 x 3 = 24
The above method is not preferred. A better way to initialize this array with the
same array elements is given below:
int test[2][3] = { {2, 4, 5}, {9, 0, 19}};
This array has 2 rows and 3 columns, which is why we have two rows of
elements with 3 elements each.
Initializing a two-dimensional
array in C++
int test[2][3][4] = {
{ {3, 4, 2, 3}, {0, -3, 9, 11}, {23, 12, 23, 2} },
{ {13, 4, 56, 3}, {5, 9, 3, 5}, {5, 1, 4, 9} }
};
The first dimension has the value 2 . So, the two elements comprising the first
dimension are:
The second dimension has the value 3 . Notice that each of the elements of the
first dimension has three elements each:
{3, 4, 2, 3}, {0, -3, 9, 11} and {23, 12, 23, 2} for Element 1.
Finally, there are four int numbers inside each of the elements of the second
dimension:
{3, 4, 2, 3}
... .. ...
... .. ...
#include <iostream>
using namespace std;
int main() {
int test[3][2] = {{2, -5},
{4, 0},
{9, 1}};
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>
using namespace std;
int main() {
int numbers[2][3];
return 0;
}
Output
Enter 6 numbers:
1
2
3
4
5
6
The numbers are:
numbers[0][0]: 1
numbers[0][1]: 2
numbers[0][2]: 3
numbers[1][0]: 4
numbers[1][1]: 5
numbers[1][2]: 6
Here, we have used a nested for loop to take the input of the 2d array. Once all
the input has been taken, we have used another nested for loop to print the
array members.
#include <iostream>
using namespace std;
int main() {
// This array can store upto 12 elements (2x3x2)
int test[2][3][2] = {
{
{1, 2},
{3, 4},
{5, 6}
},
{
{7, 8},
{9, 10},
{11, 12}
}
};
return 0;
}
Output
test[0][0][0] = 1
test[0][0][1] = 2
test[0][1][0] = 3
test[0][1][1] = 4
test[0][2][0] = 5
test[0][2][1] = 6
test[1][0][0] = 7
test[1][0][1] = 8
test[1][1][0] = 9
test[1][1][1] = 10
test[1][2][0] = 11
test[1][2][1] = 12
Previous Tutorial:
C++ Arrays
Next Tutorial:
Before you learn about passing arrays as a function argument, make sure you
know about C++ Arrays and C++ Functions.
Here, we have passed an int type array named marks to the function total() .
The size of the array is 5 .
#include <iostream>
using namespace std;
int main() {
return 0;
}
Output
Displaying marks:
Student 1: 88
Student 2: 76
Student 3: 90
Student 4: 61
Student 5: 69
Here,
display(marks);
Here, the argument marks represent the memory address of the first
element of array marks[5] .
2. However, notice the parameter of the display() function.
same address pointed by the array marks . This means that when we
manipulate m[5] in the function body, we are actually manipulating the
original array marks .
#include <iostream>
using namespace std;
// define a function
// pass a 2d array as a parameter
void display(int n[][2]) {
cout << "Displaying Values: " << endl;
for (int i = 0; i < 3; ++i) {
for (int j = 0; j < 2; ++j) {
cout << "num[" << i << "][" << j << "]: " << n[i][j] << endl;
}
}
}
int main() {
// initialize 2d array
int num[3][2] = {
{3, 4},
{9, 5},
{7, 1}
};
return 0;
}
Output
Displaying Values:
num[0][0]: 3
num[0][1]: 4
num[1][0]: 9
num[1][1]: 5
num[2][0]: 7
num[2][1]: 1
We can also pass arrays with more than 2 dimensions as a function argument.
Previous Tutorial:
Multidimensional Arrays
Next Tutorial:
C++ String
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.
• 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).
Like arrays, it is not necessary to use all the space allocated for the string. For
example:
#include <iostream>
using namespace std;
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.
int main()
{
char str[100];
cout << "Enter a string: ";
cin.get(str, 100);
Output
To read the text containing blank space, cin.get function can be used. This
function takes two arguments.
First argument is the name of the string (address of first element of string) and
second argument is the maximum size of the array.
In the above program, str is the name of the string and 100 is the maximum size
of the array.
string Object
In C++, you can also create a string object for holding strings.
Unlike using char arrays, string objects has no fixed length, and can be extended
as per your requirement.
Example 3: C++ string using string data type
#include <iostream>
using namespace std;
int main()
{
// Declaring a string object
string str;
cout << "Enter a string: ";
getline(cin, str);
Output
In this program, a string str is declared. Then the string is asked from the user.
Instead of using cin>> or cin.get() function, you can get the entered line of text
using getline() .
getline() function takes the input stream as the first parameter which
is cin and str as the location of the line to be stored.
#include <iostream>
display(str1);
display(str);
return 0;
}
void display(string s)
{
cout << "Entered string is: " << s << endl;
}
Output
In the above program, two strings are asked to enter. These are stored
in str and str1 respectively, where str is a char array and str1 is a string object.
Then, we have two functions display() that outputs the string onto the string.
The only difference between the two functions is the parameter. The
first display() function takes char array as a parameter, while the second takes
string as a parameter.
This process is known as function overloading. Learn more about Function
Overloading.
Previous Tutorial:
Next Tutorial:
C++ Structures
C++ Structures
In this article, you'll learn about structures in C++ programming; what is it, how
to define it and use it in your program.
You can easily visualize how big and messy the code would look. Also, since no
relation between the variables (information) would exist, it's going to be a
daunting task.
struct Person
{
char name[50];
int age;
float salary;
};
The structure definition is only the blueprint for the creating of variables. You
can imagine it as a datatype. When you define an integer as below:
int foo;
The int specifies that, variable foo can hold integer element only. Similarly,
structure definition only specifies that, what property a structure variable holds
when it is defined.
Note: Remember to end the declaration with a semicolon (;)
Considering you have either 32-bit or 64-bit system, the memory of float is 4
bytes, memory of int is 4 bytes and memory of char is 1 byte.
Hence, 58 bytes of memory is allocated for structure variable bill .
bill.age = 50;
#include <iostream>
using namespace std;
struct Person
{
char name[50];
int age;
float salary;
};
int main()
{
Person p1;
return 0;
}
Output
Displaying Information.
Name: Magdalena Dankova
Age: 27
Salary: 1024.4
Previous Tutorial:
C++ String
Next Tutorial:
#include <iostream>
using namespace std;
struct Person
{
char name[50];
int age;
float salary;
};
void displayData(Person); // Function declaration
int main()
{
Person p;
return 0;
}
void displayData(Person p)
{
cout << "\nDisplaying Information." << endl;
cout << "Name: " << p.name << endl;
cout <<"Age: " << p.age << endl;
cout << "Salary: " << p.salary;
}
Output
Displaying Information.
Name: Bill Jobs
Age: 55
Salary: 34233.4
In this program, user is asked to enter the name , age and salary of a Person
inside main() function.
Then, the structure variable p is to passed to a function using.
displayData(p);
The return type of displayData() is void and a single argument of type
structure Person is passed.
Then the members of structure p is displayed from this function.
#include <iostream>
using namespace std;
struct Person {
char name[50];
int age;
float salary;
};
Person getData(Person);
void displayData(Person);
int main()
{
Person p;
p = getData(p);
displayData(p);
return 0;
}
Person getData(Person p) {
void displayData(Person p)
{
cout << "\nDisplaying Information." << endl;
cout << "Name: " << p.name << endl;
cout <<"Age: " << p.age << endl;
cout << "Salary: " << p.salary;
}
p = getData(p);
A pointer variable can be created not only for native types like
( int , float , double etc.) but they can also be created for user defined types
like structure.
If you do not know what pointers are, visit C++ pointers.
Here is how you can create pointer for structures:
#include <iostream>
using namespace std;
struct temp {
int i;
float f;
};
int main() {
temp *ptr;
return 0;
}
#include <iostream>
using namespace std;
struct Distance
{
int feet;
float inch;
};
int main()
{
Distance *ptr, d;
ptr = &d;
Output
Enter feet: 4
Enter inch: 3.5
Displaying information.
Distance = 4 feet 3.5 inches
Previous Tutorial:
Next Tutorial:
C++ Enumeration
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.
An enumeration is a user-defined data type that consists of integral constants.
To define an enumeration, keyword enum is used.
enum season
{ spring = 0,
summer = 4,
autumn = 8,
winter = 12
};
// inside function
enum boolean
false, true
} check;
#include <iostream>
using namespace std;
int main()
{
week today;
today = Wednesday;
cout << "Day " << today+1;
return 0;
}
Output
Day 4
#include <iostream>
using namespace std;
enum seasons { spring = 34, summer = 4, autumn = 9, winter = 32};
int main() {
seasons s;
s = summer;
cout << "Summer = " << s << endl;
return 0;
}
Output
Summer = 4
#include <iostream>
using namespace std;
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
Size of enum variable 4 bytes.
You can accomplish the same task using C++ structures. However, working with
enums gives you efficiency along with flexibility.
enum designFlags {
ITALICS = 1,
BOLD = 2,
UNDERLINE = 4
} button;
Suppose you are designing a button for Windows application. You can set
flags ITALICS , BOLD and UNDERLINE to work with text.
There is a reason why all the integral constants are power of 2 in above
pseudocode.
// In binary
ITALICS = 00000001
BOLD = 00000010
UNDERLINE = 00000100
Since, the integral constants are power of 2, you can combine two or more flags
at once without overlapping using bitwise OR | operator. This allows you to
choose two or more flags at once. For example,
#include <iostream>
using namespace std;
enum designFlags {
BOLD = 1,
ITALICS = 2,
UNDERLINE = 4
};
int main()
{
int myDesign = BOLD | UNDERLINE;
// 00000001
// | 00000100
// ___________
// 00000101
return 0;
}
Output
When the output is 5, you always know that bold and underline is used.
}
Here, we have added italics to our design. Note, only code for italics is written
inside the if statement.
You can accomplish almost anything in C++ programming without using
enumerations. However, they can be pretty handy in certain situations. That's
what differentiates good programmers from great programmers.
Previous Tutorial:
Next Tutorial:
To handle this task, we can create three variables, say, length , breadth ,
and height along with the functions calculateArea() and calculateVolume() .
However, in C++, rather than creating separate variables and functions, we can
also wrap these related data and functions in a single place (by
creating objects). This programming paradigm is known as object-oriented
programming.
But before we can create objects and use them in C++, we first need to learn
about classes.
C++ Class
A class is a blueprint for the object.
A class is defined in C++ using keyword class followed by the name of the class.
The body of the class is defined inside the curly brackets and terminated by a
semicolon at the end.
class className {
// some data
// some functions
};
For example,
class Room {
public:
double length;
double breadth;
double height;
double calculateArea(){
return length * breadth;
}
double calculateVolume(){
return length * breadth * height;
}
};
C++ Objects
When a class is defined, only the specification for the object is defined; no
memory or storage is allocated.
To use the data and access functions defined in the class, we need to create
objects.
className objectVariableName;
We can create objects of Room class (defined in the above example) as follows:
// sample function
void sampleFunction() {
// create objects
Room room1, room2;
}
int main(){
// create objects
Room room3, room4;
}
Here, two objects room1 and room2 of the Room class are created
in sampleFunction() . Similarly, the objects room3 and room4 are created in main() .
As we can see, we can create objects of a class in any function of the program.
We can also create objects of a class within the class itself, or in other classes.
We can access the data members and member functions of a class by using
a . (dot) operator. For example,
room2.calculateArea();
This will call the calculateArea() function inside the Room class for object room2 .
Similarly, the data members can be accessed as:
room1.length = 5.5;
#include <iostream>
using namespace std;
// create a class
class Room {
public:
double length;
double breadth;
double height;
double calculateArea() {
return length * breadth;
}
double calculateVolume() {
return length * breadth * height;
}
};
int main() {
return 0;
}
Output
In this program, we have used the Room class and its object room1 to calculate the
area and volume of a room.
In main() , we assigned the values of length , breadth , and height with the code:
room1.length = 42.5;
room1.breadth = 30.8;
room1.height = 19.2;
class Test {
private:
int a;
void function1() { }
public:
int b;
void function2() { }
}
Here, a and function1() are private and are. Thus they cannot be accessed from
outside the class.
On the other hand, b and function2() are accessible from everywhere in the
program.
To learn more about public and private keywords, please visit our C++ Class
Access Modifiers tutorial.
#include <iostream>
using namespace std;
class Room {
private:
double length;
double breadth;
double height;
public:
double calculateArea() {
return length * breadth;
}
double calculateVolume() {
return length * breadth * height;
}
};
int main() {
return 0;
}
Output
The above example is nearly identical to the first example, except that the class
variables are now private.
Since the variables are now private, we cannot access them directly from main() .
Hence, using the following code would be invalid:
// invalid code
obj.length = 42.5;
obj.breadth = 30.8;
obj.height = 19.2;
Instead, we use the public function getData() to initialize the private variables
via the function parameters double len , double brth , and double hgt .
• C++ Constructors
• How to pass and return an object from a function?
Previous Tutorial:
C++ Enumeration
Next Tutorial:
C++ Constructors
C++ Constructors
In this tutorial, we will learn about the C++ constructor and its type with the help
examples.
class Wall {
public:
// create a constructor
Wall() {
// code
}
};
Here, the function Wall() is a constructor of the class Wall . Notice that the
constructor
• has the same name as the class,
• is public
#include <iostream>
using namespace std;
// declare a class
class Wall {
private:
double length;
public:
// create a constructor
Wall() {
int main() {
// create an object
Wall wall1;
return 0;
}
Output
Creating a Wall
Length = 5.5
Here, when the wall1 object is created, the Wall() constructor is called. This sets
the length variable of the object to 5.5 .
Note: If we have not defined a constructor in our class, then the C++ compiler
will automatically create a default constructor with an empty code and no
parameters.
#include <iostream>
using namespace std;
// declare a class
class Wall {
private:
double length;
double height;
public:
// create parameterized constructor
Wall(double len, double hgt) {
// initialize private variables
length = len;
height = hgt;
}
double calculateArea() {
return length * height;
}
};
int main() {
// create object and initialize data members
Wall wall1(10.5, 8.6);
Wall wall2(8.5, 6.3);
return 0;
}
Output
parameters are used to initialize the member variables length and height .
When we create an object of the Wall class, we pass the values for the member
variables as arguments. The code for this is:
With the member variables thus initialized, we can now calculate the area of the
wall with the calculateArea() function.
#include <iostream>
using namespace std;
// declare a class
class Wall {
private:
double length;
double height;
public:
// parameterized constructor
Wall(double len, double hgt) {
// initialize private variables
length = len;
height = hgt;
}
int main() {
return 0;
}
Output
In this program, we have used a copy constructor to copy the contents of one
object of the Wall class to another. The code of the copy constructor is:
Wall(Wall &obj) {
length = obj.length;
height = obj.height;
}
Notice that the parameter of this constructor has the address of an object of
the Wall class.
We then assign the values of the variables of the first object to the
corresponding variables of the second object. This is how the contents of the
object are copied.
In main() , we then create two objects wall1 and wall2 and then copy the
contents of the first object to the second with the code
Note: A constructor is primarily used to initialize objects. They are also used to
run a default code when an object is created.
Previous Tutorial:
Next Tutorial:
#include <iostream>
using namespace std;
class Student {
public:
double marks;
int main() {
Student student1(88.0), student2(56.0);
return 0;
}
Output
Average Marks = 72
Here, we have passed two Student objects student1 and student2 as arguments
to the calculateAverage() function.
Pass objects to
function in C++
#include <iostream>
using namespace std;
class Student {
public:
double marks1, marks2;
};
return student;
}
int main() {
Student student1;
// Call function
student1 = createStudent();
return 0;
}
Output
Marks1 = 96.5
Marks2 = 75
// Call function
student1 = createStudent();
Previous Tutorial:
C++ Constructors
Next Tutorial:
In C++, we can change the way operators work for user-defined types like
objects and structures. This is known as operator overloading. For example,
Suppose we have created three objects c1 , c2 and result from a class
named Complex that represents complex numbers.
Since operator overloading allows us to change how operators work, we can
redefine how the + operator works and use it to add the complex numbers
of c1 and c2 by writing the following code:
result = c1 + c2;
result = c1.addNumbers(c2);
class className {
... .. ...
public
returnType operator symbol (arguments) {
... .. ...
}
... .. ...
};
Here,
#include <iostream>
using namespace std;
class Count {
private:
int value;
public:
void display() {
cout << "Count: " << value << endl;
}
};
int main() {
Count count1;
count1.display();
return 0;
}
Output
Count: 6
Here, when we use ++count1; , the void operator ++ () is called. This increases
the value attribute for the object count1 by 1.
Note: When we overload operators, we can use it to work in any way we like. For
example, we could have used ++ to increase value by 100.
However, this makes our code confusing and difficult to understand. It's our job
as a programmer to use operator overloading properly and in a consistent and
intuitive way.
The above example works only when ++ is used as a prefix. To make ++ work as a
postfix we use this syntax.
Notice the int inside the parentheses. It's the syntax used for using unary
operators as postfix; it's not a function parameter.
#include <iostream>
using namespace std;
class Count {
private:
int value;
public:
void display() {
cout << "Count: " << value << endl;
}
};
int main() {
Count count1;
count1.display();
return 0;
}
Output
Count: 6
Count: 7
The Example 2 works when ++ is used as both prefix and postfix. However, it
doesn't work if we try to do something like this:
// Error
result = ++count1;
This is because the return type of our operator function is void . We can solve
this problem by making Count as the return type of the operator function.
Count operator ++ () {
// code
}
// return Count when ++ used as postfix
#include <iostream>
using namespace std;
class Count {
private:
int value;
public
:
// Constructor to initialize count to 5
Count() : value(5) {}
return temp;
}
return temp;
}
void display() {
cout << "Count: " << value << endl;
}
};
int main() {
Count count1, result;
return 0;
}
Output
Count: 6
Count: 7
Here, we have used the following code for prefix operator overloading:
return temp;
}
The code for the postfix operator overloading is the same as well. Notice that we
have created an object temp and returned its value to the operator function.
Also notice the code
temp.value = ++value;
The variable value belongs to the count1 object in main() because count1 is
calling the function, while temp.value belongs to the temp object.
result = num + 9;
The operator function is called using the obj1 object and obj2 is passed as an
argument to the function.
#include <iostream>
using namespace std;
class Complex {
private:
float real;
float imag;
public:
// Constructor to initialize real and imag to 0
Complex() : real(0), imag(0) {}
void input() {
cout << "Enter real and imaginary parts respectively: ";
cin >> real;
cin >> imag;
}
void output() {
if (imag < 0)
cout << "Output Complex number: " << real << imag << "i";
else
cout << "Output Complex number: " << real << "+" << imag << "i";
}
};
int main() {
Complex complex1, complex2, result;
return 0;
}
Output
However,
• using & makes our code efficient by referencing the complex2 object
instead of making a duplicate object inside the operator function.
• using const is considered a good practice because it prevents the
operator function from modifying complex2 .
Overloading binary
operators in C++
Things to Remember in C++ Operator Overloading
1. Two operators = and & are already overloaded by default in C++. For
example, to copy objects of the same class, we can directly use
the = operator. We do not need to create an operator function.
2. Operator overloading cannot change the precedence and associativity of
operators. However, if we want to change the order of evaluation,
parentheses should be used.
3. There are 4 operators that cannot be overloaded in C++. They are:
a. :: (scope resolution)
b. . (member selection)
c. .* (member selection through pointer to function)
d. ?: (ternary operator)
Previous Tutorial:
Next Tutorial:
C++ Pointers
C++ Pointers
In this tutorial, we will learn about pointers in C++ and their working with the
help of examples.
In C++, pointers are variables that store the memory addresses of other
variables.
Address in C++
If we have a variable var in our program, &var will give us its address in the
memory. For example,
Example 1: Printing Variable Addresses in C++
#include <iostream>
using namespace std;
int main()
{
// declare variables
int var1 = 3;
int var2 = 24;
int var3 = 17;
Output
C++ Pointers
As mentioned above, pointers are used to store addresses rather than values.
int *pointVar;
int* pointVar, p;
Note: The * operator is used after the data type to declare pointers.
Here, 5 is assigned to the variable var . And, the address of var is assigned to
the pointVar pointer with the code pointVar = &var .
To get the value pointed by a pointer, we use the * operator. For example:
In the above code, the address of var is assigned to pointVar . We have used
the *pointVar to get the value stored in that address.
When * is used with pointers, it's called the dereference operator. It operates
on a pointer and gives the value pointed by the address stored in the pointer.
That is, *pointVar = var .
#include <iostream>
using namespace std;
int main() {
int var = 5;
return 0;
}
Output
var = 5
Address of var (&var) = 0x61ff08
pointVar = 0x61ff08
Content of the address pointed to by pointVar (*pointVar) = 5
Working of C++
pointers
If pointVar points to the address of var , we can change the value of var by
using *pointVar .
For example,
int var = 5;
int* pointVar;
Here, pointVar and &var have the same address, the value of var will also be
changed when *pointVar is changed.
Example 3: Changing Value Pointed by Pointers
#include <iostream>
using namespace std;
int main() {
int var = 5;
int* pointVar;
// print var
cout << "var = " << var << endl;
// print *pointVar
cout << "*pointVar = " << *pointVar << endl
<< endl;
// print var
cout << "var = " << var << endl;
// print *pointVar
cout << "*pointVar = " << *pointVar << endl
<< endl;
// print var
cout << "var = " << var << endl;
// print *pointVar
cout << "*pointVar = " << *pointVar << endl;
return 0;
}
Output
var = 5
*pointVar = 5
// Wrong!
// varPoint is an address but var is not
varPoint = var;
// Wrong!
// &var is an address
// *varPoint is the value stored in &var
*varPoint = &var;
// Correct!
// varPoint is an address and so is &var
varPoint = &var;
// Correct!
// both *varPoint and var are values
*varPoint = var;
Recommended Readings:
• How to use generic data type pointers using a void pointer?
• How to represent an array using a pointer?
• How to use pointers with functions?
• How to use pointers with structures?
Previous Tutorial:
Next Tutorial:
In C++, Pointers are variables that hold addresses of other variables. Not only
can a pointer store the address of a single variable, it can also store the address
of cells of an array.
Consider this example:
int *ptr;
int arr[5];
Here, ptr is a pointer variable while arr is an int array. The code ptr =
arr; stores the address of the first element of the array in variable ptr .
Notice that we have used arr instead of &arr[0] . This is because both are the
same. So, the code below is the same as the code above.
int *ptr;
int arr[5];
ptr = &arr[0];
The addresses for the rest of the array elements are given
by &arr[1] , &arr[2] , &arr[3] , and &arr[4] .
int *ptr;
int arr[5];
ptr = arr;
Similarly, we can access the elements using the single pointer. For example,
Working of
C++ Pointers with Arrays
Note: The address between ptr and ptr + 1 differs by 4 bytes. It is
because ptr is a pointer to an int data. And, the size of int is 4 bytes in a 64-bit
operating system.
Similarly, if pointer ptr is pointing to char type data, then the address
between ptr and ptr + 1 is 1 byte. It is because the size of a character is 1 byte.
#include <iostream>
using namespace std;
int main()
{
float arr[3];
// ptr = &arr[0]
ptr = arr;
return 0;
}
Output
In the above program, we first simply printed the addresses of the array
elements without using the pointer variable ptr .
Then, we used the pointer ptr to point to the address of a[0] , ptr + 1 to point to
the address of a[1] , and so on.
In most contexts, array names decay to pointers. In simple words, array names
are converted to pointers. That's the reason why we can use pointers to access
elements of arrays.
However, we should remember that pointers and arrays are not the same.
There are a few cases where array names don't decay to pointers. To learn
more, visit: When does array name doesn't decay into a pointer?
// C++ Program to insert and display data entered by using pointer notation.
#include <iostream>
using namespace std;
int main() {
float arr[5];
return 0;
}
Output
Here,
1. We first used the pointer notation to store the numbers entered by the
user into the array arr .
Previous Tutorial:
C++ Pointers
Next Tutorial:
For example,
// pass by value
func1(num);
// pass by reference
func2(num);
return 0;
}
Notice the & in void func2(int &numRef) . This denotes that we are using the
#include <iostream>
using namespace std;
int main()
{
// initialize variables
int a = 1, b = 2;
return 0;
}
Output
Before swapping
a = 1
b = 2
After swapping
a = 2
b = 1
In this program, we passed the variables a and b to the swap() function. Notice
the function definition,
Here, we are using & to denote that the function will accept addresses as its
parameters.
Hence, the compiler can identify that instead of actual values, the reference of
the variables is passed to function parameters.
In the swap() function, the function parameters n1 and n2 are pointing to the
same value as the variables a and b respectively. Hence the swapping takes
place on actual value.
The same task can be done using the pointers. To learn about pointers, visit C++
Pointers.
#include <iostream>
using namespace std;
int main()
{
// initialize variables
int a = 1, b = 2;
Output
Before swapping
a = 1
b = 2
After swapping
a = 2
b = 1
Here, we can see the output is the same as the previous example. Notice the
line,
// &a is address of a
// &b is address of b
swap(&a, &b);
Here, the address of the variable is passed during the function call rather than
the variable.
temp = *n1;
*n1 = *n2;
*n2 = temp;
*n1 and *n2 gives the value stored at address n1 and n2 respectively.
Since n1 and n2 contain the addresses of a and b , anything is done
to *n1 and *n2 will change the actual values of a and b .
Hence, when we print the values of a and b in the main() function, the values are
changed.
Previous Tutorial:
Next Tutorial:
C++ allows us to allocate the memory of a variable or an array in run time. This is
known as dynamic memory allocation.
delete Operator
Once we no longer need to use a variable that we have declared dynamically, we
can deallocate the memory occupied by the variable.
For this, the delete operator is used. It returns the memory to the operating
system. This is known as memory deallocation.
The syntax for this operator is
delete pointerVariable;
Here, we have dynamically allocated memory for an int variable using the
pointer pointVar .
After printing the contents of pointVar , we deallocated the memory
using delete .
Note: If the program uses a large amount of unwanted memory using new , the
system may crash because there will be no memory available for the operating
system. In this case, the delete operator can help the system from crash.
#include <iostream>
using namespace std;
int main() {
// declare an int pointer
int* pointInt;
// declare a float pointer
float* pointFloat;
return 0;
}
Output
45
45.45
delete pointInt;
delete pointFloat;
#include <iostream>
using namespace std;
int main() {
int num;
cout << "Enter total number of students: ";
cin >> num;
float* ptr;
return 0;
}
Output
In this program, we have asked the user to enter the number of students and
store it in the num variable.
Then, we have allocated the memory dynamically for the float array using new .
We enter data into the array (and later print them) using pointer notation.
After we no longer need the array, we deallocate the array memory using the
code delete[] ptr; .
Notice the use of [] after delete . We use the square brackets [] in order to
denote that the memory deallocation is that of an array.
#include <iostream>
using namespace std;
class Student {
int age;
public:
void getAge() {
cout << "Age = " << age << endl;
}
};
int main() {
return 0;
}
Output
Age = 12
In this program, we have created a Student class that has a private variable age .
We have initialized age to 12 in the default constructor Student() and print its
value with the function getAge() .
In main() , we have created a Student object using the new operator and use the
pointer ptr to point to its address.
The moment the object is created, the Student() constructor initializes age to 12 .
We then call the getAge() function using the code:
ptr->getAge();
Notice the arrow operator -> . This operator is used to access class members
using pointers.
Previous Tutorial:
Next Tutorial:
C++ Inheritance
C++ Inheritance
In this tutorial, we will learn about inheritance in C++ with the help of examples.
Inheritance is one of the key features of Object-oriented programming in C++. It
allows us to create a new class (derived class) from an existing class (base class).
The derived class inherits the features from the base class and can have
additional features of its own. For example,
class Animal {
// eat() function
// sleep() function
};
Here, the Dog class is derived from the Animal class. Since Dog is derived
from Animal , members of Animal are accessible to Dog .
Inheritance in C++
Notice the use of the keyword public while inheriting Dog from Animal.
is-a relationship
Inheritance is an is-a relationship. We use inheritance only if an is-a
relationship is present between the two classes.
Here are some examples:
• A car is a vehicle.
• Orange is a fruit.
• A surgeon is a doctor.
• A dog is an animal.
#include <iostream>
using namespace std;
// base class
class Animal {
public:
void eat() {
cout << "I can eat!" << endl;
}
void sleep() {
cout << "I can sleep!" << endl;
}
};
// derived class
class Dog : public Animal {
public:
void bark() {
cout << "I can bark! Woof woof!!" << endl;
}
};
int main() {
// Create object of the Dog class
Dog dog1;
return 0;
}
Output
I can eat!
I can sleep!
I can bark! Woof woof!!
Here, dog1 (the object of derived class Dog ) can access members of the base
class Animal . It's because Dog is inherited from Animal .
#include <iostream>
#include <string>
using namespace std;
// base class
class Animal {
private:
string color;
protected:
string type;
public:
void eat() {
cout << "I can eat!" << endl;
}
void sleep() {
cout << "I can sleep!" << endl;
}
void setColor(string clr) {
color = clr;
}
string getColor() {
return color;
}
};
// derived class
class Dog : public Animal {
public:
void setType(string tp) {
type = tp;
}
void displayInfo(string c) {
cout << "I am a " << type << endl;
cout << "My color is " << c << endl;
}
void bark() {
cout << "I can bark! Woof woof!!" << endl;
}
};
int main() {
// Create object of the Dog class
Dog dog1;
return 0;
}
Output
I can eat!
I can sleep!
I can bark! Woof woof!!
I am a mammal
My color is black
Here, the variable type is protected and is thus accessible from the derived
class Dog . We can see this as we have initialized type in the Dog class using the
function setType() .
On the other hand, the private variable color cannot be initialized in Dog .
public:
void setColor(string clr) {
// Error: member "Animal::color" is inaccessible
color = clr;
}
};
Also, since the protected keyword hides data, we cannot access type directly
from an object of Dog or Animal class.
class Animal {
// code
};
The various ways we can derive classes are known as access modes. These
access modes have the following effect:
1. public: If a derived class is declared in public mode, then the members of
the base class are inherited by the derived class just as they are.
2. private: In this case, all the members of the base class
become private members in the derived class.
3. protected: The public members of the base class
become protected members in the derived class.
The private members of the base class are always private in the derived class.
To learn more, visit our C++ public, private, protected inheritance tutorial.
The member function of derived class overrides the member function of base
class.
Previous Tutorial:
Next Tutorial:
In C++ inheritance, we can derive a child class from the base class in different
access modes. For example,
class Base {
.... ... ....
};
This means that we have created a derived class from the base class in public
mode. Alternatively, we can also derive classes in protected or private modes.
These 3 keywords ( public , protected , and private ) are known as access
specifiers in C++ inheritance.
class Base {
public:
int x;
protected:
int y;
private:
int z;
};
#include <iostream>
using namespace std;
class Base {
private:
int pvt = 1;
protected:
int prot = 2;
public:
int pub = 3;
int main() {
PublicDerived object1;
cout << "Private = " << object1.getPVT() << endl;
cout << "Protected = " << object1.getProt() << endl;
cout << "Public = " << object1.pub << endl;
return 0;
}
Output
Private = 1
Protected = 2
Public = 3
Notice that the getPVT() function has been defined inside Base . But
the getProt() function has been defined inside PublicDerived .
This is because pvt , which is private in Base , is inaccessible to PublicDerived .
However, prot is accessible to PublicDerived due to public inheritance.
So, getProt() can access the protected variable from within PublicDerived .
Accessibility in public Inheritance
#include <iostream>
using namespace std;
class Base {
private:
int pvt = 1;
protected:
int prot = 2;
public:
int pub = 3;
int main() {
ProtectedDerived object1;
cout << "Private cannot be accessed." << endl;
cout << "Protected = " << object1.getProt() << endl;
cout << "Public = " << object1.getPub() << endl;
return 0;
}
Output
#include <iostream>
using namespace std;
class Base {
private:
int pvt = 1;
protected:
int prot = 2;
public:
int pub = 3;
int main() {
PrivateDerived object1;
cout << "Private cannot be accessed." << endl;
cout << "Protected = " << object1.getProt() << endl;
cout << "Public = " << object1.getPub() << endl;
return 0;
}
Output
Previous Tutorial:
C++ Inheritance
Next Tutorial:
class Base {
public:
void print() {
cout << "Base Function" << endl;
}
};
int main() {
Derived derived1;
derived1.print();
return 0;
}
Output
Derived Function
Here, the same function print() is defined in both Base and Derived classes.
So, when we call print() from the Derived object derived1 ,
the print() from Derived is executed by overriding the function in Base .
Working of function
overriding in C++
#include <iostream>
using namespace std;
class Base {
public:
void print() {
cout << "Base Function" << endl;
}
};
int main() {
Derived derived1, derived2;
derived1.print();
return 0;
}
Output
Derived Function
Base Function
derived2.Base::print();
#include <iostream>
using namespace std;
class Base {
public:
void print() {
cout << "Base Function" << endl;
}
};
class Derived : public Base {
public:
void print() {
cout << "Derived Function" << endl;
int main() {
Derived derived1;
derived1.print();
return 0;
}
Output
Derived Function
Base Function
In this program, we have called the overridden function inside the Derived class
itself.
Notice the code Base::print(); , which calls the overridden function inside
the Derived class.
Access overridden function
inside derived class in C++
#include <iostream>
using namespace std;
class Base {
public:
void print() {
cout << "Base Function" << endl;
}
};
int main() {
Derived derived1;
return 0;
}
Output
Base Function
In this program, we have created a pointer of Base type named ptr . This pointer
points to the Derived object derived1 .
When we call the print() function using ptr , it calls the overridden function
from Base .
Previous Tutorial:
class A
... .. ...
};
class B: public A
... .. ...
};
class C: public B
};
Here, class B is derived from the base class A and the class C is derived from the
derived class B .
#include <iostream>
using namespace std;
class A
{
public:
void display()
{
cout<<"Base class content.";
}
};
class B : public A
{
};
class C : public B
{
};
int main()
{
C obj;
obj.display();
return 0;
}
Output
In this program, class C is derived from class B (which is derived from base
class A ).
The obj object of class C is defined in the main() function.
When the display() function is called, display() in class A is executed. It's
because there is no display() function in class C and class B .
The compiler first looks for the display() function in class C . Since the function
doesn't exist there, it looks for the function in class B (as C is derived from B ).
The function also doesn't exist in class B , so the compiler looks for it in
class A (as B is derived from A ).
If display() function exists in C , the compiler overrides display() of
class A (because of member function overriding).
#include <iostream>
using namespace std;
class Mammal {
public:
Mammal()
{
cout << "Mammals can give direct birth." << endl;
}
};
class WingedAnimal {
public:
WingedAnimal()
{
cout << "Winged animal can flap." << endl;
}
};
};
int main()
{
Bat b1;
return 0;
}
Output
Suppose, two base classes have a same function which is not overridden in
derived class.
If you try to call the function using the object of the derived class, compiler
shows error. It's because compiler doesn't know which function to call. For
example,
class base1
{
public:
void someFunction( )
{ .... ... .... }
};
class base2
{
void someFunction( )
{ .... ... .... }
};
class derived : public base1, public base2
{
};
int main()
{
derived obj;
obj.someFunction() // Error!
}
This problem can be solved using scope resolution function to specify which
function to class either base1or base2
int main()
class base_class {
... .. ...
... .. ...
... .. ...
}
class third_derived_class: public base_class {
... .. ...
Previous Tutorial:
Next Tutorial:
Similarly, protected members can only be accessed by derived classes and are
inaccessible from outside. For example,
class MyClass {
private:
int member1;
}
int main() {
MyClass obj;
class className {
... .. ...
friend returnType functionName(arguments);
... .. ...
}
#include <iostream>
using namespace std;
class Distance {
private:
int meter;
// friend function
friend int addFive(Distance);
public:
Distance() : meter(0) {}
};
// friend function definition
int addFive(Distance d) {
int main() {
Distance D;
cout << "Distance: " << addFive(D);
return 0;
}
Output
Distance: 5
Here, addFive() is a friend function that can access both private and public data
members.
Though this example gives us an idea about the concept of a friend function, it
doesn't show any meaningful use.
#include <iostream>
using namespace std;
// forward declaration
class ClassB;
class ClassA {
public:
// constructor to initialize numA to 12
ClassA() : numA(12) {}
private:
int numA;
class ClassB {
public:
// constructor to initialize numB to 1
ClassB() : numB(1) {}
private:
int numB;
int main() {
ClassA objectA;
ClassB objectB;
cout << "Sum: " << add(objectA, objectB);
return 0;
}
Output
Sum: 13
In this program, ClassA and ClassB have declared add() as a friend function.
Thus, this function can access private data of both classes.
One thing to notice here is the friend function inside ClassA is using the ClassB .
However, we haven't defined ClassB at this point.
// inside classA
friend int add(ClassA, ClassB);
// forward declaration
class ClassB;
class ClassB;
class ClassA {
// ClassB is a friend class of ClassA
friend class ClassB;
... .. ...
}
class ClassB {
... .. ...
}
When a class is declared a friend class, all the member functions of the friend
class become friend functions.
Since classB is a friend class, we can access all members of classA from
inside classB .
However, we cannot access members of ClassB from inside classA . It is because
friend relation in C++ is only granted, not taken.
Example 3: C++ friend Class
#include <iostream>
using namespace std;
// forward declaration
class ClassB;
class ClassA {
private:
int numA;
public:
// constructor to initialize numA to 12
ClassA() : numA(12) {}
};
class ClassB {
private:
int numB;
public:
// constructor to initialize numB to 1
ClassB() : numB(1) {}
int main() {
ClassB objectB;
cout << "Sum: " << objectB.add();
return 0;
}
Output
Sum: 13
Here, ClassB is a friend class of ClassA . So, ClassB has access to the members
of classA .
In ClassB , we have created a function add() that returns the sum
of numA and numB .
Since ClassB is a friend class, we can create objects of ClassA inside of ClassB .
Previous Tutorial:
Next Tutorial:
Basically, a virtual function is used in the base class in order to ensure that the
function is overridden. This especially applies to cases where a pointer of base
class points to an object of a derived class.
For example, consider the code below:
class Base {
public:
void print() {
// code
}
};
class Derived : public Base {
public:
void print() {
// code
}
};
int main() {
Derived derived1;
Base* base1 = &derived1;
return 0;
}
In order to avoid this, we declare the print() function of the Base class as virtual
by using the virtual keyword.
class Base {
public:
virtual void print() {
// code
}
};
#include <iostream>
using namespace std;
class Base {
public:
virtual void print() {
cout << "Base Function" << endl;
}
};
int main() {
Derived derived1;
return 0;
}
Output
Derived Function
For example,
class Base {
public:
virtual void print() {
// code
}
};
If we use a function prototype in Derived class and define that function outside
of the class, then we use the following code:
// function definition
void Derived::print() {
// code
}
When using virtual functions. it is possible to make mistakes while declaring the
member functions of the derived classes.
Using the override identifier prompts the compiler to display error messages
when these mistakes are made.
Otherwise, the program will simply compile but the virtual function will not be
overridden.
class Animal {
private:
string type;
... .. ...
public:
Animal(): type("Animal") {}
... .. ...
};
Now, let us suppose that our program requires us to create two public functions
for each class:
1. getType() to return the value of type
2. print() to print the value of type
We could create both these functions in each class separately and override
them, which will be long and tedious.
Or we could make getType() virtual in the Animal class, then create a single,
separate print() function that accepts a pointer of Animal type as its argument.
We can then use this single function to override the virtual function.
class Animal {
... .. ...
public:
... .. ...
virtual string getType {...}
};
... .. ...
... .. ...
This will make the code shorter, cleaner, and less repetitive.
class Animal {
private:
string type;
public:
// constructor to initialize type
Animal() : type("Animal") {}
public:
// constructor to initialize type
Dog() : type("Dog") {}
public:
// constructor to initialize type
Cat() : type("Cat") {}
int main() {
Animal* animal1 = new Animal();
Animal* dog1 = new Dog();
Animal* cat1 = new Cat();
print(animal1);
print(dog1);
print(cat1);
return 0;
}
Output
Animal: Animal
Animal: Dog
Animal: Cat
Here, we have used the virtual function getType() and an Animal pointer ani in
order to avoid repeating the print() function in every class.
Templates are powerful features of C++ which allows you to write generic
programs. In simple terms, you can create a single function or a class to work
with different data types using templates.
Templates are often used in larger codebase for the purpose of code reusability
and flexibility of the programs.
• Function Templates
• Class Templates
Function Templates
A function template works in a similar to a normal function, with one key
difference.
A single function template can work with different data types at once but, a
single normal function can only work with one set of data types.
Normally, if you need to perform identical operations on two or more types of
data, you use function overloading to create two functions with the required
function declaration.
In the above code, T is a template argument that accepts different data types
(int, float), and class is a keyword.
You can also use keyword typename instead of class in the above example.
When, an argument of a data type is passed to someFunction( ) , compiler
generates a new version of someFunction() for the given data type.
#include <iostream>
using namespace std;
// template function
template <class T>
T Large(T n1, T n2)
{
return (n1 > n2) ? n1 : n2;
}
int main()
{
int i1, i2;
float f1, f2;
char c1, c2;
return 0;
}
Output
In the above program, a function template Large() is defined that accepts two
arguments n1 and n2 of data type T . T signifies that argument can be of any data
type.
Large() function returns the largest among the two arguments using a
simple conditional operation.
Inside the main() function, variables of three different data
types: int , float and char are declared. The variables are then passed to
the Large() function template as normal functions.
During run-time, when an integer is passed to the template function, compiler
knows it has to generate a Large() function to accept the int arguments and
does so.
Similarly, when floating-point data and char data are passed, it knows the
argument data types and generates the Large() function accordingly.
This way, using only a single function template replaced three identical normal
functions and made your code maintainable.
#include <iostream>
using namespace std;
Swap(i1, i2);
Swap(f1, f2);
Swap(c1, c2);
return 0;
}
Output
i1 = 1
i2 = 2
f1 = 1.1
f2 = 2.2
c1 = a
c2 = b
i1 = 2
i2 = 1
f1 = 2.2
f2 = 1.1
c1 = b
c2 = a
Class Templates
Like function templates, you can also create class templates for generic class
operations.
Sometimes, you need a class implementation that is same for all classes, only
the data types used are different.
Normally, you would need to create a different class for each data type OR
create different member variables and functions within a single class.
This will unnecessarily bloat your code base and will be hard to maintain, as a
change is one class/function should be performed on all classes/functions.
However, class templates make it easy to reuse the same code for all data types.
To create a class template object, you need to define the data type inside a <
> when creation.
className<dataType> classObject;
For example:
className<int> classObject;
className<float> classObject;
className<string> classObject;
Program to add, subtract, multiply and divide two numbers using class
template
#include <iostream>
using namespace std;
public:
Calculator(T n1, T n2)
{
num1 = n1;
num2 = n2;
}
void displayResult()
{
cout << "Numbers are: " << num1 << " and " << num2 << "." <<
endl;
cout << "Addition is: " << add() << endl;
cout << "Subtraction is: " << subtract() << endl;
cout << "Product is: " << multiply() << endl;
cout << "Division is: " << divide() << endl;
}
int main()
{
Calculator<int> intCalc(2, 1);
Calculator<float> floatCalc(2.4, 1.2);
Output
Int results:
Numbers are: 2 and 1.
Addition is: 3
Subtraction is: 1
Product is: 2
Division is: 2
Float results:
Numbers are: 2.4 and 1.2.
Addition is: 3.6
Subtraction is: 1.2
Product is: 2.88
Division is: 2
We can create a single function to work with different data types by using a
template.
In the above code, T is a template argument that accepts different data types
( int , float , etc.), and typename is a keyword.
When an argument of a data type is passed to functionName() , the compiler
generates a new version of functionName() for the given data type.
Calling a Function Template
Once we've declared and defined a function template, we can call it in other
functions or templates (such as the main() function) with the following syntax
functionName<dataType>(parameter1, parameter2,...);
We can then call it in the main() function to add int and double numbers.
int main() {
int result1;
double result2;
// calling with int parameters
result1 = add<int>(2, 3);
cout << result1 << endl;
return 0;
}
Function Call based on data types
#include <iostream>
using namespace std;
int main() {
int result1;
double result2;
// calling with int parameters
result1 = add<int>(2, 3);
cout << "2 + 3 = " << result1 << endl;
Output
2 + 3 = 5
2.2 + 3.3 = 5.5
Share on:
C++ Polymorphism
In this tutorial, we will learn about polymorphism in C++ with the help of
examples.
The + operator in C++ is used to perform two specific functions. When it is used
with numbers (integers and floating-point numbers), it performs addition.
int a = 5;
int b = 6;
int sum = a + b; // sum = 11
And when we use the + operator with strings, it performs string concatenation.
For example,
#include <iostream>
using namespace std;
int main() {
// Call function with 2 int parameters
cout << "Sum 1 = " << sum(5, 6) << endl;
// Call function with 2 double parameters
cout << "Sum 2 = " << sum(5.5, 6.6) << endl;
return 0;
}
Output
Sum 1 = 11
Sum 2 = 12.1
Sum 3 = 18
We cannot use operator overloading for basic types such as int , double , etc.
Operator overloading is basically function overloading, where different operator
functions have the same symbol but different operands.
And, depending on the operands, different operator functions are executed. For
example,
class Count {
private:
int value;
public:
void display() {
cout << "Count: " << value << endl;
}
};
int main() {
Count count1;
count1.display();
return 0;
}
Output
Count: 6
So, different functions are executed depending on the object calling the
function.
#include <iostream>
using namespace std;
class Base {
public:
virtual void print() {
cout << "Base Function" << endl;
}
};
int main() {
Derived derived1;
return 0;
}
Output
Derived Function
Here, we have used a print() function in the Base class and the same function in
the Derived class
When we call print() using the Derived object derived1 , it overrides
the print() function of Base by executing the print() function of
the Derived class.
It's a runtime polymorphism because the function call is not resolved by the
compiler, but it is resolved in the runtime instead.
To learn more, visit our C++ Function Overriding tutorial.
Using virtual functions in the base class ensures that the function can be
overridden in these cases.
Thus, virtual functions actually fall under function overriding. For example,
#include <iostream>
using namespace std;
class Base {
public:
virtual void print() {
cout << "Base Function" << endl;
}
};
int main() {
Derived derived1;
return 0;
}
Output
Derived Function
Here, we have used a virtual function print() in the Base class to ensure that it is
overridden by the function in the Derived class.
Virtual functions are runtime polymorphism.
To learn more, visit our C++ Virtual Functions tutorial.
Why Polymorphism?
Polymorphism allows us to create consistent code. For example,
Suppose we need to calculate the area of a circle and a square. To do so, we can
create a Shape class and derive two classes Circle and Square from it.
In this case, it makes sense to create a function having the same
name calculateArea() in both the derived classes rather than creating functions
with different names, thus making our code more consistent.
Share on:
Introduction
Decisions and Loops
Functions
Arrays and Strings
Structures
Operator overloading
All Examples
#include <iostream>
#include <cmath>
using namespace std;
int main() {
if (discriminant > 0) {
x1 = (-b + sqrt(discriminant)) / (2*a);
x2 = (-b - sqrt(discriminant)) / (2*a);
cout << "Roots are real and different." << endl;
cout << "x1 = " << x1 << endl;
cout << "x2 = " << x2 << endl;
}
else if (discriminant == 0) {
cout << "Roots are real and same." << endl;
x1 = -b/(2*a);
cout << "x1 = x2 =" << x1 << endl;
}
else {
realPart = -b/(2*a);
imaginaryPart =sqrt(-discriminant)/(2*a);
cout << "Roots are complex and different." << endl;
cout << "x1 = " << realPart << "+" << imaginaryPart << "i" << endl;
cout << "x2 = " << realPart << "-" << imaginaryPart << "i" << endl;
}
return 0;
}
Output
In this program, sqrt() library function is used to find the square root of a
number.
#include <iostream>
using namespace std;
bool checkPrimeNumber(int);
int main() {
int n;
if (checkPrimeNumber(n))
cout << n << " is a prime number.";
else
cout << n << " is not a prime number.";
return 0;
}
bool checkPrimeNumber(int n) {
bool isPrime = true;
Output
To do this, size() function is used to find the length of a string object. Then, the
for loop is iterated until the end of the string.
In each iteration, occurrence of character is checked and if found, the value
of count is incremented by 1.
#include <iostream>
using namespace std;
int main()
{
string str = "C++ Programming is awesome";
char checkCharacter = 'a';
int count = 0;
cout << "Number of " << checkCharacter << " = " << count;
return 0;
}
Output
Number of a = 2
In the example below, loop is iterated until the null character '\0' is
encountered. Null character indicates the end of the string.
In each iteration, the occurrence of the character is checked.
Example 2: Find Frequency of Characters in a C-style
String
#include <iostream>
Output
Number of m = 2
#include <iostream>
using namespace std;
struct student
{
char name[50];
int roll;
float marks;
};
int main()
{
student s;
cout << "Enter information," << endl;
cout << "Enter name: ";
cin >> s.name;
cout << "Enter roll number: ";
cin >> s.roll;
cout << "Enter marks: ";
cin >> s.marks;
Enter information,
Enter name: Bill
Enter roll number: 4
Enter marks: 55.6
Displaying Information,
Name: Bill
Roll: 4
Marks: 55.6
#include <iostream>
using namespace std;
struct Distance{
int feet;
float inch;
}d1 , d2, sum;
int main()
{
cout << "Enter 1st distance," << endl;
cout << "Enter feet: ";
cin >> d1.feet;
cout << "Enter inch: ";
cin >> d1.inch;
sum.feet = d1.feet+d2.feet;
sum.inch = d1.inch+d2.inch;
cout << endl << "Sum of distances = " << sum.feet << " feet " << sum.inch
<< " inches";
return 0;
}
Output
#include <iostream>
using namespace std;
int main() {
complexNumber num1, num2, complexSum;
char signOfImag;
cout << "For 1st complex number," << endl;
cout << "Enter real and imaginary parts respectively:" << endl;
cin >> num1.real >> num1.imag;
cout << "Sum = " << complexSum.real << signOfImag << complexSum.imag <<
"i";
return 0;
}
Output
/// Use Ternary Operator to adjust the sign of the imaginary number
complexSum.imag = (complexSum.imag > 0) ? complexSum.imag : -complexSum.imag;