You are on page 1of 115

https://www.programiz.

com/
http://www.studytonight.com
Simple Examples
Program 1:
Basic C++ Program
// Author: Bert G. Wachsmuth
// Version: Oct. 2000
#include <iostream.h>

int main(void)
{
cout << Hello, this is my first C++ program << endl;
return 0;
}
Program 2:

Data Types and Variable names


// Author: Bert G. Wachsmuth
// Version: Oct. 2000
#include <iostream.h>

int main(void)
{
double x = 3.5;
int i = 10;
char c = B;
// the following three lines works fine:
x = x + 2*x; // x has the new value 10.5
double y = x + i; // y has the value 13.5
double z = 12345610E32; // z has large range
// the following two lines is not okay:
int j = x + i; // can not store double as an int
int k = 1234567890123456790; // range of k is not large enough
return 0;
}

Program 3:

Input/Output
#include <iostream.h>

int main(void)
{
double x = 0.0; // its good practice to initialize all
variables by assigning a value
cout << Please enter a number: ;
cin >> x;
cout << You entered << x << , whose square is << x*x << endl;
return 0;
}
Program 4:

Basic Operations
int x = 10;
int y = 20;
int z = (x + y) * (x - y) / (2 * y) % y; // has value 2
Computational Shortcuts
int x = 10;
x++; // x has value 11
x -= 10; // x has value 1;
x *= 5; // x has value 5;

Program 5:

Logical Operators and Tests and Conditional Execution


Assuming i is some integer, what is the difference between:
if ( (i % 2) == 0)
cout << i is an even number << endl;
cout << i is an odd number << endl;

if ( (i % 2) == 0)
cout << i is an even number << endl;
else
cout << i is an odd number << endl;

if (i < 0)
cout << i is negative << endl;
else if ( (i % 2) == 0)
cout << i is even and not negative << endl;
else if ( (i % 2) == 1)
cout << i is odd and not negative << endl;
else
cout << You have found a new type of integer << endl;

What is the output of:

double x = 3;
double y = 10;
if ( ((x % 2) == 0) && !(y < x))
cout << This << endl;
else
cout << That << endl;

Which of the following tests could crash? Why or why not?

if ( (x != 0) && (1/x > 2))


cout << Reciprocal of x is bigger than 2 << endl;
if ( (x > 0) || (sqrt(x) < 9))
cout << x is between 0 and 3 << endl;
Program 6:

Loops
How often do the following loops execute:

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


cout << How often: << i << endl;

int i = 0;
while (i < 10)
{ cout << i << endl;
i += 4;
}

What is the final value of sum:

int sum = 0;
for (int i = 1; i < 5; i++)
sum += i;

What are the three ingredients for every loop?

Program 7:

Functions
How do you use each of the functions defined below:

void fun1(void)
{ /* does something */ }
void fun2(int i)
{ /* does something */ }
double fun3(int i, double x)
{ /* does something */ }

Define a function that computes the area of a rectangle. It should not contain any cin or cout statements.

Define a function that asks the user to enter a double number and returns that number.

Program 8:

Reference and Value Parameters


What is the value of x and y at the end of the main function:

void f1(double x, double y)


{ x = y;
y = 2;
}
void f2(double& x, double y)
{ x = -1;
y = -2;
}
int main(void)
{ double x = 10;
double y = 10;
f1(x, y);
f2(y, x);
cout << x = << x << , y = << y << endl;
return 0;
}

If f1 and f2 are defined as above, which of the following calls are invalid:

f1(10, 20);
f2(30, 40);
double x = 10;
f1(x, x);
f2(x, x);
f2(10, x);
f2(x, 10);

Program 9:

Scope and Scope Rules


Which lines in the following code are invalid, and whats the output if you were to ignore those errors:

#include <iostream.h>

double x = 10;

void f1(double y)
{ x = 20;
y = 30;
}
void f2(double x)
{ x = 40;
y =50;
}
void f3(double& z)
{ z = 60;
x = 70;
}
int main(void)
{ double y = 2;
f1(x+y);
f2(y);
f3(x - y);
f3(x);
cout << x = << x << , y = << y << endl;
return 0;
}

C++ for Loop Syntax


for(initializationStatement; testExpression; updateStatement) {
// codes

where, only testExpression is mandatory.

How for loop works?


1. The initialization statement is executed only once at the beginning.

2. Then, the test expression is evaluated.

3. If the test expression is false, for loop is terminated. But if the test
expression is true, codes inside body of for loop is executed and update
expression is updated.

4. Again, the test expression is evaluated and this process repeats until the
test expression is false.
Flowchart of for Loop in C++

Example 1: C++ for Loop


// C++ Program to find factorial of a number
// Factorial on n = 1*2*3*...*n

#include <iostream>
using namespace std;
int main()
{
int i, n, factorial = 1;

cout << "Enter a positive integer: ";


cin >> n;

for (i = 1; i <= n; ++i) {


factorial *= i; // factorial = factorial * i;
}

cout<< "Factorial of "<<n<<" = "<<factorial;


return 0;
}

Output

Enter a positive integer: 5

Factorial of 5 = 120

In the program, user is asked to enter a positive integer which is stored in


variable n(suppose user entered 5). Here is the working of for loop:

1. Initially, i is equal to 1, test expression is true, factorial becomes 1.

2. i is updated to 2, test expression is true, factorial becomes 2.

3. i is updated to 3, test expression is true, factorial becomes 6.

4. i is updated to 4, test expression is true, factorial becomes 24.

5. i is updated to 5, test expression is true, factorial becomes 120.


6. i is updated to 6, test expression is false, for loop is terminated.

In the above program, variable i is not used outside of the for loop. In such
cases, it is better to declare the variable in for loop (at initialization statement).

#include <iostream>
using namespace std;

int main()
{
int n, factorial = 1;

cout << "Enter a positive integer: ";


cin >> n;

for (int i = 1; i <= n; ++i) {


factorial *= i; // factorial = factorial * i;
}

cout<< "Factorial of "<<n<<" = "<<factorial;


return 0;
}

Check out these examples to learn more:

C++ Program to Calculate Sum of Natural Numbers


C++ Program to Find Factorial
C++ Program to Generate Multiplication Table

C++ while Loop


The syntax of a while loop is:
while (testExpression)

// codes

where, testExpression is checked on each entry of the while loop.

How while loop works?


The while loop evaluates the test expression.

If the test expression is true, codes inside the body of while loop is
evaluated.

Then, the test expression is evaluated again. This process goes on until
the test expression is false.

When the test expression is false, while loop is terminated.


Flowchart of while Loop

Example 1: C++ while Loop


// C++ Program to compute factorial of a number
// Factorial of n = 1*2*3...*n

#include <iostream>
using namespace std;

int main()
{
int number, i = 1, factorial = 1;

cout << "Enter a positive integer: ";


cin >> number;

while ( i <= number) {


factorial *= i; //factorial = factorial * i;
++i;
}

cout<<"Factorial of "<< number <<" = "<< factorial;


return 0;
}

Output

Enter a positive integer: 4

Factorial of 4 = 24

In this program, user is asked to enter a positive integer which is stored in


variable number. Let's suppose, user entered 4.

Then, the while loop starts executing the code. Here's how while loop works:

1. Initially, i = 1, test expression i <= number is true and factorial becomes 1.

2. Variable i is updated to 2, test expression is true, factorial becomes 2.

3. Variable i is updated to 3, test expression is true, factorial becomes 6.

4. Variable i is updated to 4, test expression is true, factorial becomes 24.

5. Variable i is updated to 5, test expression is false and while loop is


terminated.

C++ do...while Loop


The do...while loop is a variant of the while loop with one important difference.
The body of do...while loop is executed once before the test expression is
checked.

The syntax of do..while loop is:

do {

// codes;

while (testExpression);

How do...while loop works?


The codes inside the body of loop is executed at least once. Then, only
the test expression is checked.

If the test expression is true, the body of loop is executed. This process
continues until the test expression becomes false.

When the test expression is false, do...while loop is terminated.


Flowchart of do...while Loop

Example 2: C++ do...while Loop


// C++ program to add numbers until user enters 0

#include <iostream>
using namespace std;

int main()
{
float number, sum = 0.0;

do {
cout<<"Enter a number: ";
cin>>number;
sum += number;
}
while(number != 0.0);

cout<<"Total sum = "<<sum;

return 0;
}

Output

Enter a number: 2

Enter a number: 3

Enter a number: 4

Enter a number: -4

Enter a number: 2

Enter a number: 4.4

Enter a number: 2

Enter a number: 0

C++ break Statement


The break; statement terminates a loop (for, while and do..while loop) and
a switch statementimmediately when it appears.
Syntax of break
break;

In real practice, break statement is almost always used inside the body of
conditional statement (if...else) inside the loop.

How break statement works?

Example 1: C++ break


C++ program to add all number entered by user until user enters 0.
// C++ Program to demonstrate working of break statement

#include <iostream>
using namespace std;
int main() {
float number, sum = 0.0;

// test expression is always true


while (true)
{
cout << "Enter a number: ";
cin >> number;

if (number != 0.0)
{
sum += number;
}
else
{
// terminates the loop if number equals 0.0
break;
}

}
cout << "Sum = " << sum;

return 0;
}

Output
Enter a number: 4

Enter a number: 3.4

Enter a number: 6.7

Enter a number: -4.5

Enter a number: 0

Sum = 9.6

In the above program, the test expression is always true.

The user is asked to enter a number which is stored in the variable number. If the
user enters any number other than 0, the number is added to sum and stored to it.

Again, the user is asked to enter another number. When user enters 0, the test
expression inside if statement is false and body of else is executed which
terminates the loop.

Finally, the sum is displayed.

C++ continue Statement


It is sometimes necessary to skip a certain test condition within a loop. In such
case, continue; statement is used in C++ programming.

Syntax of continue
continue;
In practice, continue; statement is almost always used inside a conditional
statement.

Working of continue Statement

Example 2: C++ continue


C++ program to display integer from 1 to 10 except 6 and 9.

#include <iostream>
using namespace std;

int main()
{
for (int i = 1; i <= 10; ++i)
{
if ( i == 6 || i == 9)
{
continue;
}
cout << i << "\t";
}
return 0;
}

Output

1 2 3 4 5 7 8 10

In above program, when i is 6 or 9, execution of statement cout << i << "\t"; is


skipped inside the loop using continue; statement.

Check out these examples to learn more:

C++ Program to Check Whether a Number is Prime or Not


C++ Program to Display Prime Numbers Between Two Intervals
C++ Programs To Create Pyramid and Pattern

C++ Class
Before you create an object in C++, you need to define a class.

A class is a blueprint for the object.

We can think of class as a sketch (prototype) of a house. It contains all the


details about the floors, doors, windows etc. Based on these descriptions we
build the house. House is the object.

As, many houses can be made from the same description, we can create many
objects from a class.
How to define a class in C++?
A class is defined in C++ using keyword class followed by the name of class.

The body of class is defined inside the curly brackets and terminated by a
semicolon at the end.

class className

// some data

// some functions

};

Example: Class in C++


class Test
{
private:
int data1;
float data2;

public:
void function1()
{ data1 = 2; }

float function2()
{
data2 = 3.5;
return data2;
}
};

Here, we defined a class named Test.

This class has two data members: data1 and data2 and two member
functions: function1()and function2().

Keywords: private and public


You may have noticed two keywords: private and public in the above example.

The private keyword makes data and functions private. Private data and
functions can be accessed only from inside the same class.

The public keyword makes data and functions public. Public data and functions
can be accessed out of the class.

Here, data1 and data2 are private members where


as function1() and function2() are public members.

If you try to access private data from outside of the class, compiler throws error.
This feature in OOP is known as data hiding.

C++ Objects
When 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, you need to create
objects.
Syntax to Define Object in C++
className objectVariableName;

You can create objects of Test class (defined in above example) as follows:

class Test
{
private:
int data1;
float data2;

public:
void function1()
{ data1 = 2; }

float function2()
{
data2 = 3.5;
return data2;
}
};

int main()
{
Test o1, o2;
}

Here, two objects o1 and o2 of Test class are created.


In the above class Test, data1 and data2 are data members
and function1() and function2() are member functions.

How to access data member and member


function in C++?
You can access the data members and member functions by using a . (dot)
operator. For example,

o2.function1();

This will call the function1() function inside the Test class for objects o2.

Similarly, the data member can be accessed as:

o1.data2 = 5.5;

It is important to note that, the private members can be accessed only from
inside the class.

So, you can use o2.function1(); from any function or class in the above
example. However, the code o1.data2 = 5.5; should always be inside the
class Test.

Example: Object and Class in C++


Programming
// Program to illustrate the working of objects and class in C++
Programming
#include <iostream>
using namespace std;
class Test
{
private:
int data1;
float data2;

public:

void insertIntegerData(int d)
{
data1 = d;
cout << "Number: " << data1;
}

float insertFloatData()
{
cout << "\nEnter data: ";
cin >> data2;
return data2;
}
};

int main()
{
Test o1, o2;
float secondDataOfObject2;

o1.insertIntegerData(12);
secondDataOfObject2 = o2.insertFloatData();
cout << "You entered " << secondDataOfObject2;
return 0;
}

Output

Number: 12

Enter data: 23.3

You entered 23.3

In this program, two data members data1 and data2 and two member
functions insertIntegerData() and insertFloatData() are defined
under Test class.

Two objects o1 and o2 of the same class are declared.

The insertIntegerData() function is called for the o1 object using:

o1.insertIntegerData(12);

This sets the value of data1 for object o1 to 12.

Then, the insertFloatData() function for object o2 is called and the return value
from the function is stored in variable secondDataOfObject2 using:

secondDataOfObject2 = o2.insertFloatData();

In this program, data2 of o1 and data1 of o2 are not used and contains garbage
value.

You should also check these topics to learn more on objects and classes:

C++ Constructors
How to pass and return object from a function?

Check out these examples to learn more:

Increment ++ and Decrement -- Operator Overloading in C++


Programming
C++ Program to Subtract Complex Number Using Operator Overloading

Example: Operator overloading in C++


Programming
#include <iostream>
using namespace std;

class Test
{
private:
int count;

public:
Test(): count(5){}

void operator ++()


{
count = count+1;
}
void Display() { cout<<"Count: "<<count; }
};

int main()
{
Test t;
// this calls "function void operator ++()" function
++t;
t.Display();
return 0;
}

C++ Arrays
In this article, you will learn to work with arrays. You will learn to declare,
initialize and, access array elements in C++ programming.

In programming, one of the frequently arising problem is to handle numerous


data of same type.

Consider this situation, you are taking a survey of 100 people and you have to
store their age. To solve this problem in C++, you can create an integer array
having 100 elements.

An array is a collection of data that holds fixed number of values of same type.
For example:
int age[100];

Here, the age array can hold maximum of 100 elements of integer type.

The size and type of arrays cannot be changed after its declaration.

How to declare an array in C++?


dataType arrayName[arraySize];

For example,

float mark[5];

Here, we declared an array, mark, of floating-point type and size 5. Meaning, it


can hold 5 floating-point values.

Elements of an Array and How to access


them?
You can access elements of an array by using indices.

Suppose you declared an array mark as above. The first element is mark[0],
second element is mark[1] and so on.
Few key notes:
Arrays have 0 as the first index not 1. In this example, mark[0] is the first
element.

If the size of an array is n, to access the last element, (n-1) index is used.
In this example, mark[4] is the last element.

Suppose the starting address of mark[0] is 2120d. Then, the next


address, a[1], will be 2124d, address of a[2] will be 2128d and so on. It's
because the size of a float is 4 bytes.

How to initialize an array in C++


programming?
It's possible to initialize an array during declaration. For example,

int mark[5] = {19, 10, 8, 17, 9};

Another method to initialize array during declaration:

int mark[] = {19, 10, 8, 17, 9};

Here,

mark[0] is equal to 19
mark[1] is equal to 10

mark[2] is equal to 8

mark[3] is equal to 17

mark[4] is equal to 9

How to insert and print array elements?


int mark[5] = {19, 10, 8, 17, 9}

// insert different value to third element


mark[3] = 9;

// take input from the user and insert in third element


cin >> mark[2];

// take input from the user and insert in (i+1)th element


cin >> mark[i];

// print first element of an array


cout << mark[0];

// print ith element of an array


cin >> mark[i-1];
Example: C++ Array
C++ program to store and calculate the sum of 5 numbers entered by the
user using arrays.

#include <iostream>
using namespace std;

int main()
{
int numbers[5], sum = 0;
cout << "Enter 5 numbers: ";

// Storing 5 number entered by user in an array


// Finding the sum of numbers entered
for (int i = 0; i < 5; ++i)
{
cin >> numbers[i];
sum += numbers[i];
}

cout << "Sum = " << sum << endl;

return 0;
}

Output

Enter 5 numbers: 3

4
5

Sum = 18

Things to remember when working with


arrays in C++
Suppose you declared an array of 10 elements. Let's say,

int testArray[10];

You can use the array members from testArray[0] to testArray[9].

If you try to access array elements outside of its bound, let's say testArray[14],
the compiler may not show any error. However, this may cause unexpected
output (undefined behavior).

Before going further, checkout these C++ array articles:

How to pass arrays to a function?

Relation between arrays and pointers

Multidimensional arrays

Check out these examples to learn more:

C++ Program to Calculate Average of Numbers Using Arrays


C++ Program to Find Largest Element of an Array
C++ Program to Calculate Standard Deviation

Example: Calculate Average of Numbers


Using Arrays
#include <iostream>
using namespace std;

int main()
{
int n, i;
float num[100], sum=0.0, average;

cout << "Enter the numbers of data: ";


cin >> n;

while (n > 100 || n <= 0)


{
cout << "Error! number should in range of (1 to 100)." <<
endl;
cout << "Enter the number again: ";
cin >> n;
}

for(i = 0; i < n; ++i)


{
cout << i + 1 << ". Enter number: ";
cin >> num[i];
sum += num[i];
}
average = sum / n;
cout << "Average = " << average;

return 0;
}

Output

Enter the numbers of data: 6

1. Enter number: 45.3

2. Enter number: 67.5

3. Enter number: -45.6

4. Enter number: 20.34

5. Enter number: 33

6. Enter number: 45.6

Average = 27.69

Example: Display Largest Element of an


array
#include <iostream>
using namespace std;

int main()
{
int i, n;
float arr[100];

cout << "Enter total number of elements(1 to 100): ";


cin >> n;
cout << endl;

// Store number entered by the user


for(i = 0; i < n; ++i)
{
cout << "Enter Number " << i + 1 << " : ";
cin >> arr[i];
}

// Loop to store largest number to arr[0]


for(i = 1;i < n; ++i)
{
// Change < to > if you want to find the smallest element
if(arr[0] < arr[i])
arr[0] = arr[i];
}
cout << "Largest element = " << arr[0];

return 0;
}

Output

Enter total number of elements: 8


Enter Number 1: 23.4

Enter Number 2: -34.5

Enter Number 3: 50

Enter Number 4: 33.5

Enter Number 5: 55.5

Enter Number 6: 43.7

Enter Number 7: 5.7

Enter Number 8: -66.5

Largest element = 55.5

Example: Calculate Standard Deviation by


Passing it to Function
#include <iostream>
#include <cmath>
using namespace std;

float calculateSD(float data[]);

int main()
{
int i;
float data[10];

cout << "Enter 10 elements: ";


for(i = 0; i < 10; ++i)
cin >> data[i];

cout << endl << "Standard Deviation = " << calculateSD(data);

return 0;
}

float calculateSD(float data[])


{
float sum = 0.0, mean, standardDeviation = 0.0;

int i;

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


{
sum += data[i];
}

mean = sum/10;

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


standardDeviation += pow(data[i] - mean, 2);

return sqrt(standardDeviation / 10);


}
Output

Enter 10 elements: 1

10

Standard Deviation = 2.872281

C++ Pointers and Arrays


In this article, you'll learn about the relation between arrays and pointers,
and use them efficiently in your program.
Pointers are the variables that hold address. Not only can pointers store address
of a single variable, it can also store address of cells of an array.

Consider this example:

int* ptr;

int a[5];

ptr = &a[2]; // &a[2] is the address of third element of a[5].

Suppose, pointer needs to point to the fourth element of an array, that is, hold
address of fourth array element in above case.
Since ptr points to the third element in the above example, ptr + 1 will point to
the fourth element.

You may think, ptr + 1 gives you the address of next byte to the ptr. But it's not
correct.

This is because pointer ptr is a pointer to an int and size of int is fixed for a
operating system (size of int is 4 byte of 64-bit operating system). Hence, the
address between ptrand ptr + 1 differs by 4 bytes.

If pointer ptr was pointer to char then, the address between ptr and ptr +
1 would have differed by 1 byte since size of a character is 1 byte.

Example 1: C++ Pointers and Arrays


C++ Program to display address of elements of an array using both array
and pointers

#include <iostream>
using namespace std;

int main()
{
float arr[5];
float *ptr;

cout << "Displaying address using arrays: " << endl;


for (int i = 0; i < 5; ++i)
{
cout << "&arr[" << i << "] = " << &arr[i] << endl;
}

// ptr = &arr[0]
ptr = arr;
cout<<"\nDisplaying address using pointers: "<< endl;
for (int i = 0; i < 5; ++i)
{
cout << "ptr + " << i << " = "<< ptr + i << endl;
}

return 0;
}

Output

Displaying address using arrays:

&arr[0] = 0x7fff5fbff880

&arr[1] = 0x7fff5fbff884

&arr[2] = 0x7fff5fbff888

&arr[3] = 0x7fff5fbff88c

&arr[4] = 0x7fff5fbff890

Displaying address using pointers:

ptr + 0 = 0x7fff5fbff880

ptr + 1 = 0x7fff5fbff884

ptr + 2 = 0x7fff5fbff888
ptr + 3 = 0x7fff5fbff88c

ptr + 4 = 0x7fff5fbff890

In the above program, a different pointer ptr is used for displaying the address of
array elements arr.

But, array elements can be accessed using pointer notation by using same array
name arr. For example:

int arr[3];

&arr[0] is equivalent to arr

&arr[1] is equivalent to arr + 1

&arr[2] is equivalen to arr + 2

Example 2: Pointer and Arrays


C++ Program to display address of array elements using pointer notation.

#include <iostream>
using namespace std;

int main() {
float arr[5];

cout<<"Displaying address using pointers notation: "<< endl;


for (int i = 0; i < 5; ++i) {
cout << arr + i <<endl;
}

return 0;
}

Output

Displaying address using pointers notation:

0x7fff5fbff8a0

0x7fff5fbff8a4

0x7fff5fbff8a8

0x7fff5fbff8ac

0x7fff5fbff8b0

You know that, pointer ptr holds the address and expression *ptr gives the value
stored in the address.

Similarly, you can get the value stored in the pointer ptr + 1 using *(ptr + 1).

Consider this code below:

int ptr[5] = {3, 4, 5, 5, 3};

&ptr[0] is equal to ptr and *ptr is equal to ptr[0]

&ptr[1] is equal to ptr + 1 and *(ptr + 1) is equal to ptr[1]

&ptr[2] is equal to ptr + 2 and *(ptr + 2) is equal to ptr[2]


&ptr[i] is equal to ptr + i and *(ptr + i) is equal to ptr[i]

Example 3: C++ Pointer and Array


C++ Program to insert and display data entered by using pointer notation.

#include <iostream>
using namespace std;

int main() {
float arr[5];

// Inserting data using pointer notation


cout << "Enter 5 numbers: ";
for (int i = 0; i < 5; ++i) {
cin >> *(arr + i) ;
}

// Displaying data using pointer notation


cout << "Displaying data: " << endl;
for (int i = 0; i < 5; ++i) {
cout << *(arr + i) << endl ;
}

return 0;
}

Output

Enter 5 numbers: 2.5


3.5

4.5

Displaying data:

2.5

3.5

4.5

Check out these examples to learn more:

C++ Program to Access Elements of an Array Using Pointer

Example 1: Passing by reference without


pointers
#include <iostream>
using namespace std;

// Function prototype
void swap(int&, int&);

int main()
{
int a = 1, b = 2;
cout << "Before swapping" << endl;
cout << "a = " << a << endl;
cout << "b = " << b << endl;

swap(a, b);

cout << "\nAfter swapping" << endl;


cout << "a = " << a << endl;
cout << "b = " << b << endl;

return 0;
}

void swap(int& n1, int& n2) {


int temp;
temp = n1;
n1 = n2;
n2 = temp;
}

Output

Before swapping

a = 1

b = 2
After swapping

a = 2

b = 1

In main(), two integer variables a and b are defined. And those integers are
passed to a function swap() by reference.

Compiler can identify this is pass by reference because function definition is void
swap(int& n1, int& n2) (notice the & sign after data type).

Only the reference (address) of the variables a and b are received in


the swap() function and swapping takes place in the original address of the
variables.

In the swap() function, n1 and n2 are formal arguments which are actually same
as variables a and b respectively.

There is another way of doing this same exact task using pointers.

Example 2: Passing by reference using


pointers
#include <iostream>
using namespace std;

// Function prototype
void swap(int*, int*);

int main()
{
int a = 1, b = 2;
cout << "Before swapping" << endl;
cout << "a = " << a << endl;
cout << "b = " << b << endl;

swap(&a, &b);

cout << "\nAfter swapping" << endl;


cout << "a = " << a << endl;
cout << "b = " << b << endl;
return 0;
}

void swap(int* n1, int* n2) {


int temp;
temp = *n1;
*n1 = *n2;
*n2 = temp;
}

The output of this example is same as before.

In this case, the address of variable is passed during function call rather than the
variable itself.

swap(&a, &b); // &a is address of a and &b is address of b

Since the address is passed instead of value, dereference operator must be used
to access the value stored in that address.

void swap(int* n1, int* n2) {


... .. ...

The *n1 and *n2 gives the value stored at address n1 and n2 respectively.

Since n1 contains the address of a, anything done to *n1 changes the value
of a in main() function as well. Similarly, b will have same value as *n2.

Example: Access Array Elements Using


Pointer
#include <iostream>
using namespace std;

int main()
{
int data[5];
cout << "Enter elements: ";

for(int i = 0; i < 5; ++i)


cin >> data[i];

cout << "You entered: ";


for(int i = 0; i < 5; ++i)
cout << endl << *(data + i);

return 0;
}

Output
Enter elements: 1

You entered: 1

In this program, the five elements are entered by the user and stored in the
integer array data.

Then, the data array is accessed using a for loop and each element in the array
is printed onto the screen.

C++ Inheritance
In this article, you'll learn everything about inheritance in C++. More
specifically, what is inheritance and different ways to implement it with
examples.
Inheritance is one of the key features of Object-oriented programming in C++. It
allows user to create a new class (derived class) from an existing class(base
class).

The derived class inherits all the features from the base class and can have
additional features of its own.

Why inheritance should be used?


Suppose, in your game, you want three characters - a maths teacher,
a footballer and a businessman.

Since, all of the characters are persons, they can walk and talk. However, they
also have some special skills. A maths teacher can teach maths, a footballer
can play football and a businessman can run a business.

You can individually create three classes who can walk, talk and perform their
special skill as shown in the figure below.
In each of the classes, you would be copying the same code for walk and talk for
each character.

If you want to add a new feature - eat, you need to implement the same code for
each character. This can easily become error prone (when copying) and
duplicate codes.

It'd be a lot easier if we had a Person class with basic features like talk, walk,
eat, sleep, and add special skills to those features as per our characters. This is
done using inheritance.

Using inheritance, now you don't implement the same code for walk and talk for
each class. You just need to inherit them.

So, for Maths teacher (derived class), you inherit all features of a Person (base
class) and add a new feature TeachMaths. Likewise, for a footballer, you inherit
all the features of a Person and add a new feature PlayFootball and so on.
This makes your code cleaner, understandable and extendable.

It is important to remember: When working with inheritance, each derived class


should satisfy the condition whether it "is a" base class or not. In the example
above, Maths teacher is a Person, Footballer is a Person. You cannot have:
Businessman is a Business.

Implementation of Inheritance in C++


Programming
class Person

... .. ...

};

class MathsTeacher : public Person

... .. ...

};

class Footballer : public Person

{
.... .. ...

};

In the above example, class Person is a base class and


classes MathsTeacher and Footballerare the derived from Person.

The derived class appears with the declaration of a class followed by a colon, the
keyword public and the name of base class from which it is derived.

Since, MathsTeacher and Footballer are derived from Person, all data member
and member function of Person can be accessible from them.

Example: Inheritance in C++


Programming
Create game characters using the concept of inheritance.

#include <iostream>
using namespace std;

class Person
{
public:
string profession;
int age;

Person(): profession("unemployed"), age(16) { }


void display()
{
cout << "My profession is: " << profession << endl;
cout << "My age is: " << age << endl;
walk();
talk();
}
void walk() { cout << "I can walk." << endl; }
void talk() { cout << "I can talk." << endl; }
};

// MathsTeacher class is derived from base class Person.


class MathsTeacher : public Person
{
public:
void teachMaths() { cout << "I can teach Maths." << endl;
}
};

// Footballer class is derived from base class Person.


class Footballer : public Person
{
public:
void playFootball() { cout << "I can play Football." <<
endl; }
};

int main()
{
MathsTeacher teacher;
teacher.profession = "Teacher";
teacher.age = 23;
teacher.display();
teacher.teachMaths();

Footballer footballer;
footballer.profession = "Footballer";
footballer.age = 19;
footballer.display();
footballer.playFootball();

return 0;
}

Output

My profession is: Teacher

My age is: 23

I can walk.

I can talk.

I can teach Maths.

My profession is: Footballer

My age is: 19

I can walk.

I can talk.

I can play Football.


In this program, Person is a base class, while MathsTeacher and Footballer are
derived from Person.

Person class has two data members - profession and age. It also has two
member functions - walk() and talk().

Both MathsTeacher and Footballer can access all data members and member
functions of Person.

However, MathsTeacher and Footballer have their own member functions as


well: teachMaths() and playFootball() respectively. These functions are only
accessed by their own class.

In the main() function, a new MathsTeacher object teacher is created.

Since, it has access to Person's data members, profession and age of teacher is
set. This data is displayed using the display() function defined in
the Person class. Also, the teachMaths() function is called, defined in
the MathsTeacher class.

Likewise, a new Footballer object footballer is also created. It has access


to Person's data members as well, which is displayed by invoking
the display() function. The playFootball()function only accessible by the
footballer is called then after.

Access specifiers in Inheritance


When creating a derived class from a base class, you can use different access
specifiers to inherit the data members of the base class.

These can be public, protected or private.

In the above example, the base class Person has been inherited public-ly
by MathsTeacherand Footballer.

Learn more about Public, Protected and Private Inheritance in C++.


Member Function Overriding in Inheritance
Suppose, base class and derived class have member functions with same name
and arguments.

If you create an object of the derived class and try to access that member
function, the member function in derived class is only invoked.

The member function of derived class overrides the member function of base
class.

Learn more about Function overriding in C++.

Public, Protected and Private


Inheritance in C++ Programming
In this article, you'll learn to use public, protected and private inheritance in
C++. You'll learn where and how it is used, with examples.

You can declare a derived class from a base class with different access control,
i.e., public inheritance, protected inheritance or private inheritance.
#include <iostream>

using namespace std;

class base

.... ... ....

};

class derived : access_specifier base

.... ... ....

};

Note: Either public, protected or private keyword is used in place


of access_specifierterm used in the above code.

Example of public, protected and private


inheritance in C++
class base
{
public:
int x;
protected:
int y;
private:
int z;
};

class publicDerived: public base


{
// x is public
// y is protected
// z is not accessible from publicDerived
};

class protectedDerived: protected base


{
// x is protected
// y is protected
// z is not accessible from protectedDerived
};

class privateDerived: private base


{
// x is private
// y is private
// z is not accessible from privateDerived
}

In the above example, we observe the following things:

base has three member variables: x, y and z which


are public, protected and private member respectively.
publicDerived inherits variables x and y as public and protected. z is not
inherited as it is a private member variable of base.

protectedDerived inherits variables x and y. Both variables become


protected. z is not inherited
If we derive a class derivedFromProtectedDerived from protectedDerived,
variables x and y are also inherited to the derived class.

privateDerived inherits variables x and y. Both variables become


private. z is not inherited
If we derive a class derivedFromPrivateDerived from privateDerived,
variables x and y are not inherited because they are private variables of
privateDerived.

Accessibility in Public Inheritance


private protected public
Accessibility
variables variables variables

Accessible from own class? yes yes yes

Accessible from derived


no yes yes
class?

Accessible from 2nd derived


no yes yes
class?

Accessibility in Protected Inheritance


private protected
Accessibility public variables
variables variables

Accessible from own


yes yes yes
class?

yes
Accessible from derived
no yes (inherited as protected
class?
variables)
private protected
Accessibility public variables
variables variables

Accessible from 2nd


no yes yes
derived class?

Accessibility in Private Inheritance


private protected
Accessibility public variables
variables variables

Accessible from own


yes yes yes
class?

yes yes
Accessible from derived
no (inherited as private (inherited as private
class?
variables) variables)

Accessible from 2nd


no no no
derived class?

C++ Function Overriding


In this article, you will learn about function overriding. Also, you will learn
how can assess the overridden function of the base class in C++
programming.
Inheritance allows software developers to derive a new class from the existing
class. The derived class inherits features of the base class (existing class).

Suppose, both base class and derived class have a member function with same
name and arguments (number and type of arguments).

If you create an object of the derived class and call the member function which
exists in both classes (base and derived), the member function of the derived
class is invoked and the function of the base class is ignored.

This feature in C++ is known as function overriding.


How to access the overridden function in the
base class from the derived class?
To access the overridden function of the base class from the derived class, scope
resolution operator :: is used. For example,

If you want to access getData() function of the base class, you can use the
following statement in the derived class.

Base::getData();
Example 1: C++ Multilevel Inheritance
#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

Base class content.

Example 2: Multiple Inheritance in C++


Programming
This program calculates the area and perimeter of an rectangle but, to perform
this program, multiple inheritance is used.

#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;
}
};

class Bat: public Mammal, public WingedAnimal {

};

int main()
{
Bat b1;
return 0;
}

Output

Mammals can give direct birth.


Winged animal can flap.

Prefix Increment ++ operator overloading


with return type
#include <iostream>
using namespace std;

class Check
{
private:
int i;
public:
Check(): i(0) { }

// Return type is Check


Check operator ++()
{
Check temp;
++i;
temp.i = i;

return temp;
}

void Display()
{ cout << "i = " << i << endl; }
};
int main()
{
Check obj, obj1;
obj.Display();
obj1.Display();

obj1 = ++obj;

obj.Display();
obj1.Display();

return 0;
}

Output

i = 0

i = 0

i = 1

i = 1

This program is si

Example 4: Operator Overloading of


Decrement -- Operator
Decrement operator can be overloaded in similar way as increment operator.

#include <iostream>
using namespace std;

class Check
{
private:
int i;
public:
Check(): i(3) { }
Check operator -- ()
{
Check temp;
temp.i = --i;
return temp;
}

// Notice int inside barcket which indicates postfix


decrement.
Check operator -- (int)
{
Check temp;
temp.i = i--;
return temp;
}

void Display()
{ cout << "i = "<< i <<endl; }
};

int main()
{
Check obj, obj1;
obj.Display();
obj1.Display();

// Operator function is called, only then value of obj is


assigned to obj1
obj1 = --obj;
obj.Display();
obj1.Display();

// Assigns value of obj to obj1, only then operator function


is called.
obj1 = obj--;
obj.Display();
obj1.Display();

return 0;
}

Output

i = 3

i = 3

i = 2

i = 2

i = 1

i = 2
Also, unary operators like: !, ~ etc can be overloaded in similar manner.

C++ Operator Overloading


In C++, it's possible to change the way operator works (for user-defined
types). In this article, you will learn to implement operator overloading
feature.

The meaning of an operator is always same for variable of basic types like: int,
float, double etc. For example: To add two integers, + operator is used.

However, for user-defined types (like: objects), you can redefine the way operator
works. For example:

If there are two objects of a class that contains string as its data members. You
can redefine the meaning of + operator and use it to concatenate those strings.

This feature in C++ programming that allows programmer to redefine the


meaning of an operator (when they operate on class objects) is known as
operator overloading.
Why is operator overloading used?
You can write any C++ program without the knowledge of operator overloading.
However, operator operating are profoundly used by programmers to make
program intuitive. For example,

You can replace the code like:

calculation = add(multiply(a, b),divide(a, b));

to

calculation = (a*b)+(a/b);

How to overload operators in C++


programming?
To overload an operator, a special operator function is defined inside the class
as:

class className
{
... .. ...
public
returnType operator symbol (arguments)
{
... .. ...
}
... .. ...
};

Here, returnType is the return type of the function.

The returnType of the function is followed by operator keyword.


Symbol is the operator symbol you want to overload. Like: +, <, -, ++

You can pass arguments to the operator function in similar way as


functions.

Example: Operator overloading in C++


Programming
#include <iostream>
using namespace std;

class Test
{
private:
int count;

public:
Test(): count(5){}

void operator ++()


{
count = count+1;
}
void Display() { cout<<"Count: "<<count; }
};

int main()
{
Test t;
// this calls "function void operator ++()" function
++t;
t.Display();
return 0;
}

Output

Count: 6

This function is called when ++ operator operates on the object of Test class
(object t in this case).

In the program,void operator ++ () operator function is defined


(inside Test class).

This function increments the value of count by 1 for t object.

Things to remember
1. Operator overloading allows you to redefine the way operator works for
user-defined types only (objects, structures). It cannot be used for built-in
types (int, float, char etc.).

2. Two operators = and & are already overloaded by default in C++. For
example: To copy objects of same class, you can directly use = operator.
You do not need to create an operator function.

3. Operator overloading cannot change the precedence and associatively of


operators. However, if you want to change the order of evaluation,
parenthesis should be used.

4. There are 4 operators that cannot be overloaded in C++. They


are :: (scope resolution), . (member selection), .* (member selection
through pointer to function) and ?:(ternary operator).
Following best practices while using operator
overloading
Operator overloading allows you to define the way operator works (the way you
want).

In the above example, ++ operator operates on object to increase the value of


data member count by 1.

void operator ++()

count = count+1;

However, if you use the following code. It decreases the value of count by 100
when ++operator is used.

void operator ++()

count = count-100;

This may be technically correct. But, this code is confusing and, difficult to
understand and debug.

It's your job as a programmer to use operator overloading properly and in


consistent way.
In the above example, the value of count increases by 1 when ++ operator is
used. However, this program is incomplete in sense that you cannot use code
like:

t1 = ++t

It is because the return type of the operator function is void.

Visit these pages to learn more on:

How to overload increment operator in right way?

How to overload binary operator - to subtract complex numbers?

Example: C++ Structure


C++ Program to assign data to members of a structure variable and display it.

#include <iostream>
using namespace std;

struct Person
{
char name[50];
int age;
float salary;
};

int main()
{
Person p1;
cout << "Enter Full name: ";
cin.get(p1.name, 50);
cout << "Enter age: ";
cin >> p1.age;
cout << "Enter salary: ";
cin >> p1.salary;

cout << "\nDisplaying Information." << endl;


cout << "Name: " << p1.name << endl;
cout <<"Age: " << p1.age << endl;
cout << "Salary: " << p1.salary;

return 0;
}

Output

Enter Full name: Magdalena Dankova

Enter age: 27

Enter salary: 1024.4

Displaying Information.

Name: Magdalena Dankova

Age: 27

Salary: 1024.4
Here a structure Person is declared which has three
members name, age and salary.

Inside main() function, a structure variable p1 is defined. Then, the user is asked
to enter information and data entered by user is displayed.

assing structure to function in C++


A structure variable can be passed to a function in similar way as normal
argument. Consider this example:

Example 1: C++ Structure and Function


#include <iostream>
using namespace std;

struct Person
{
char name[50];
int age;
float salary;
};

void displayData(Person); // Function declaration

int main()
{
Person p;
cout << "Enter Full name: ";
cin.get(p.name, 50);
cout << "Enter age: ";
cin >> p.age;
cout << "Enter salary: ";
cin >> p.salary;

// Function call with structure variable as an argument


displayData(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

Enter Full name: Bill Jobs

Enter age: 55

Enter salary: 34233.4


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.

C++ Virtual Function


In this article, you will learn about virtual function and where to use it. Also,
you will learn about pure virtual function and abstract class.
A virtual function is a member function in base class that you expect to redefine
in derived classes.

Before going into detail, let's build an intuition on why virtual functions are
needed in the first place.

An Example to Begin With


Let us assume, we are working on a game (weapons specifically).

We created the Weapon class and derived two classes Bomb and Gun to load
features of respective weapons.

#include <iostream>
using namespace std;

class Weapon
{
public:
void loadFeatures()
{ cout << "Loading weapon features.\n"; }
};

class Bomb : public Weapon


{
public:
void loadFeatures()
{ cout << "Loading bomb features.\n"; }
};

class Gun : public Weapon


{
public:
void loadFeatures()
{ cout << "Loading gun features.\n"; }
};

int main()
{
Weapon *w = new Weapon;
Bomb *b = new Bomb;
Gun *g = new Gun;

w->loadfeatures();
b->loadFeatures();
g->loadFeatures();
return 0;
}

Output

Loading weapon features.

Loading bomb features.

Loading gun features.

We defined three pointer objects w, b and g of


classes Weapon, Bomb and Gunrespectively. And, we called loadFeatures() member
function of each objects using:

w->loadfeatures();

b->loadFeatures();

g->loadFeatures();

Works perfectly!

However, our game project started getting bigger and bigger. And, we decided to
create a separate Loader class to load weapon features.

This Loader class loads additional features of a weapon depending on which


weapon is selected.

class Loader
{
public:
void loadFeatures(Weapon *weapon)
{
weapon->features();
}
};

The loadFeatures() loads the feature of a specific weapon.

Let's try to implement our Loader class


#include <iostream>
using namespace std;

class Weapon
{
public:
void features()
{ cout << "Loading weapon features.\n"; }
};

class Bomb : public Weapon


{
public:
void features()
{ cout << "Loading bomb features.\n"; }
};

class Gun : public Weapon


{
public:
void features()
{ cout << "Loading gun features.\n"; }
};

class Loader
{
public:
void loadFeatures(Weapon *weapon)
{
weapon->features();
}
};

int main()
{
Loader *l = new Loader;
Weapon *w;
Bomb b;
Gun g;

w = &b;
l->loadFeatures(w);

w = &g;
l->loadFeatures(w);

return 0;
}

Output
Loading weapon features.

Loading weapon features.

Loading weapon features.

Our implementation seemed correct. However, weapon features was loaded 3


times. Why?

Initially, the Weapon object w is pointing to the b object (of Bomb) class. And, we
tried to load the features of Bomb object by passing it to loadFeatures() function
using l object to pointer (of Loader class).

Similarly, we tried to load the features of Gun object.

However, the loadFeatures() function of the Loader class takes pointer to object
of a Weaponclass as an argument:

void loadFeatures(Weapon *weapon)

That's the reason weapon features are loaded 3 times. To solve this issue, we
need to make function of base class (Weapon class) virtual using virtual keyword.

class Weapon
{
public:
virtual void features()
{ cout << "Loading weapon features.\n"; }
};
Example: Using Virtual Function to Solve
the Problem
#include <iostream>
using namespace std;

class Weapon
{
public:
virtual void features()
{ cout << "Loading weapon features.\n"; }
};

class Bomb : public Weapon


{
public:
void features()
{ cout << "Loading bomb features.\n"; }
};

class Gun : public Weapon


{
public:
void features()
{ cout << "Loading gun features.\n"; }
};

class Loader
{
public:
void loadFeatures(Weapon *weapon)
{
weapon->features();
}
};

int main()
{
Loader *l = new Loader;
Weapon *w;
Bomb b;
Gun g;

w = &b;
l->loadFeatures(w);

w = &g;
l->loadFeatures(w);

return 0;
}

Output

Loading weapon features.

Loading bomb features.

Loading gun features.


Also, notice that, the l->loadFeatures(w) function calls the function of different
classes depending upon what l object is pointing.

Using virtual function made our code not only clearer but flexible too.

If we want to add another weapon (let's say knife), we can easily add and load
features of it. How?

class Knife : public Weapon


{
public:
void features()
{ cout << "Loading knife features.\n"; }
};

And, in main() function.

Knife k;

w = &k;

l->loadFeatures(w);

It's worth noticing that we didn't changed anything in the Loader class to load
features of knife.

C++ Abstract class and Pure virtual


Function
The goal of object-oriented programming is to divide a complex problem into
small sets. This helps understand and work with problem in an efficient way.

Sometimes, it's desirable to use inheritance just for the case of better
visualization of the problem.
In C++, you can create an abstract class that cannot be instantiated (you cannot
create object of that class). However, you can derive a class from it and
instantiate object of the derived class.

Abstract classes are the base class which cannot be instantiated.

A class containing pure virtual function is known as abstract class.

Pure Virtual Function


A virtual function whose declaration ends with =0 is called a pure virtual function.
For example,

class Weapon

public:

virtual void features() = 0;

};

Here, the pure virtual function is

virtual void features() = 0

And, the class Weapon is an abstract class.


Example: Abstract Class and Pure Virtual
Function
#include <iostream>
using namespace std;

// Abstract class
class Shape
{
protected:
float l;
public:
void getData()
{
cin >> l;
}

// virtual Function
virtual float calculateArea() = 0;
};

class Square : public Shape


{
public:
float calculateArea()
{ return l*l; }
};

class Circle : public Shape


{
public:
float calculateArea()
{ return 3.14*l*l; }
};

int main()
{
Square s;
Circle c;

cout << "Enter length to calculate the area of a square: ";


s.getData();
cout<<"Area of square: " << s.calculateArea();
cout<<"\nEnter radius to calculate the area of a circle: ";
c.getData();
cout << "Area of circle: " << c.calculateArea();

return 0;
}

Output

Enter length to calculate the area of a square: 4

Area of square: 16

Enter radius to calculate the area of a circle: 5

Area of circle: 78.5

In this program, pure virtual function virtual float area() = 0; is defined inside
the Shapeclass.
One important thing to note is that, you should override the pure virtual function
of the base class in the derived class. If you fail the override it, the derived class
will become an abstract class as well.

Use of Constructor in C++


Suppose you are working on 100's of Person objects and the default value of a
data member age is 0. Initialising all objects manually will be a very tedious task.

Instead, you can define a constructor that initialises age to 0. Then, all you have
to do is create a Person object and the constructor will automatically initialise
the age.

These situations arise frequently while handling array of objects.

Also, if you want to execute some code immediately after an object is created,
you can place the code inside the body of the constructor.

Example 1: Constructor in C++


Calculate the area of a rectangle and display it.

#include <iostream>
using namespace std;

class Area
{
private:
int length;
int breadth;

public:
// Constructor
Area(): length(5), breadth(2){ }
void GetLength()
{
cout << "Enter length and breadth respectively: ";
cin >> length >> breadth;
}

int AreaCalculation() { return (length * breadth); }

void DisplayArea(int temp)


{
cout << "Area: " << temp;
}
};

int main()
{
Area A1, A2;
int temp;

A1.GetLength();
temp = A1.AreaCalculation();
A1.DisplayArea(temp);

cout << endl << "Default Area when value is not taken from
user" << endl;

temp = A2.AreaCalculation();
A2.DisplayArea(temp);

return 0;
}

In this program, class Area is created to handle area related functionalities. It has
two data members length and breadth.

A constructor is defined which initialises length to 5 and breadth to 2.

We also have three additional member functions GetLength(),


AreaCalculation() and DisplayArea() to get length from the user, calculate the
area and display the area respectively.

When, objects A1 and A2 are created, the length and breadth of both objects are
initialized to 5 and 2 respectively, because of the constructor.

Then, the member function GetLength() is invoked which takes the value
of length and breadth from the user for object A1. This changes the length and
breadth of the object A1.

Then, the area for the object A1 is calculated and stored in variable temp by
calling AreaCalculation() function and finally, it is displayed.

For object A2, no data is asked from the user. So, the length and breadth remains
5 and 2 respectively.

Then, the area for A2 is calculated and displayed which is 10.

Output

Enter length and breadth respectively: 6

Area: 42

Default Area when value is not taken from user

Area: 10
Constructor Overloading
Constructor can be overloaded in a similar way as function overloading.

Overloaded constructors have the same name (name of the class) but different
number of arguments.

Depending upon the number and type of arguments passed, specific constructor
is called.

Since, there are multiple constructors present, argument to the constructor


should also be passed while creating an object.

Example 2: Constructor overloading


// Source Code to demonstrate the working of overloaded
constructors
#include <iostream>
using namespace std;

class Area
{
private:
int length;
int breadth;

public:
// Constructor with no arguments
Area(): length(5), breadth(2) { }

// Constructor with two arguments


Area(int l, int b): length(l), breadth(b){ }
void GetLength()
{
cout << "Enter length and breadth respectively: ";
cin >> length >> breadth;
}

int AreaCalculation() { return length * breadth; }

void DisplayArea(int temp)


{
cout << "Area: " << temp << endl;
}
};

int main()
{
Area A1, A2(2, 1);
int temp;

cout << "Default Area when no argument is passed." << endl;


temp = A1.AreaCalculation();
A1.DisplayArea(temp);

cout << "Area when (2,1) is passed as argument." << endl;


temp = A2.AreaCalculation();
A2.DisplayArea(temp);

return 0;
}
For object A1, no argument is passed while creating the object.

Thus, the constructor with no argument is invoked which initialises length to 5


and breadthto 2. Hence, area of the object A1 will be 10.

For object A2, 2 and 1 are passed as arguments while creating the object.

Thus, the constructor with two arguments is invoked which


initialises length to l (2 in this case) and breadth to b (1 in this case). Hence,
area of the object A2 will be 2.

Output

Default Area when no argument is passed.

Area: 10

Area when (2,1) is passed as argument.

Area: 2

Default Copy Constructor


An object can be initialized with another object of same type. This is same as
copying the contents of a class to another class.

In the above program, if you want to initialise an object A3 so that it contains


same values as A2, this can be performed as:

....

int main()

{
Area A1, A2(2, 1);

// Copies the content of A2 to A3

Area A3(A2);

OR,

Area A3 = A2;

You might think, you need to create a new constructor to perform this task. But,
no additional constructor is needed. This is because the copy constructor is
already built into all classes by default.

Constructors
Constructors are special class functions which performs initialization of every object. The
Compiler calls the Constructor whenever an object is created. Constructors iitialize values to
object members after storage is allocated to the object.
class A

int x;

public:

A(); //Constructor

};

While defining a contructor you must remeber that the name of constructor will be same as
the name of the class, and contructors never have return type.
Constructors can be defined either inside the class definition or outside class definition using
class name and scope resolution :: operator.
class A

int i;

public:
A(); //Constructor declared

};

A::A() // Constructor definition

i=1;

Types of Constructors
Constructors are of three types :

1. Default Constructor

2. Parametrized Constructor

3. Copy COnstructor

Default Constructor
Default constructor is the constructor which doesn't take any argument. It has no parameter.
Syntax :
class_name ()

{ Constructor Definition }

Example :
class Cube

int side;

public:

Cube()

side=10;

};
int main()

Cube c;

cout << c.side;

Output : 10
In this case, as soon as the object is created the constructor is called which initializes its data
members.
A default constructor is so important for initialization of object members, that even if we do
not define a constructor explicitly, the compiler will provide a default constructor implicitly.
class Cube

int side;

};

int main()

Cube c;

cout << c.side;

Output : 0
In this case, default constructor provided by the compiler will be called which will initialize the
object data members to default value, that will be 0 in this case.

Parameterized Constructor
These are the constructors with parameter. Using this Constructor you can provide different
values to data members of different objects, by passing the appropriate values as argument.
Example :
class Cube

int side;

public:

Cube(int x)

side=x;

};
int main()

Cube c1(10);

Cube c2(20);

Cube c3(30);

cout << c1.side;

cout << c2.side;

cout << c3.side;

OUTPUT : 10 20 30
By using parameterized construcor in above case, we have initialized 3 objects with user
defined values. We can have any number of parameters in a constructor.

Copy Constructor
These are special type of Constructors which takes an object as argument, and is used to
copy values of data members of one object into other object. We will study copy constructors
in detail later.

Constructor Overloading
Just like other member functions, constructors can also be overloaded. Infact when you have
both default and parameterized constructors defined in your class you are having
Overloaded Constructors, one with no parameter and other with parameter.
You can have any number of Constructors in a class that differ in parameter list.
class Student

int rollno;

string name;

public:

Student(int x)

rollno=x;

name="None";

Student(int x, string str)


{

rollno=x ;

name=str ;

};

int main()

Student A(10);

Student B(11,"Ram");

In above case we have defined two constructors with different parameters, hence
overloading the constructors.
One more important thing, if you define any constructor explicitly, then the compiler will not
provide default constructor and you will have to define it yourself.
In the above case if we write Student S; in main(), it will lead to a compile time error,
because we haven't defined default constructor, and compiler will not provide its default
constructor because we have defined other parameterized constructors.

Destructors
Destructor is a special class function which destroys the object as soon as the scope of
object ends. The destructor is called automatically by the compiler when the object goes out
of scope.
The syntax for destructor is same as that for the constructor, the class name is used for the
name of destructor, with a tilde ~ sign as prefix to it.
class A

public:

~A();

};

Destructors will never have any arguments.

Example to see how Constructor and Destructor is called


class A

{
A()

cout << "Constructor called";

~A()

cout << "Destructor called";

};

int main()

A obj1; // Constructor Called

int x=1

if(x)

A obj2; // Constructor Called

} // Destructor Called for obj2

} // Destructor called for obj1

Single Definition for both Default and Parameterized Constructor


In this example we will use default argument to have a single definition for both defualt and
parameterized constructor.
class Dual

int a;

public:

Dual(int x=0)

a=x;

};

int main()
{

Dual obj1;

Dual obj2(10);

Here, in this program, a single Constructor definition will take care for both these object
initializations. We don't need separate default and parameterized constructors.

Polymorphism
Polymorphism means having multiple forms of one thing. In inheritance, polymorphism is
done, by method overriding, when both super and sub class have member function with
same declaration bu different definition.

Function Overriding
If we inherit a class into the derived class and provide a definition for one of the base class's
function again inside the derived class, then that function is said to be overridden, and this
mechanism is called Function Overriding

Requirements for Overriding

1. Inheritance should be there. Function overriding cannot be done within a class. For

this we require a derived class and a base class.

2. Function that is redefined must have exactly the same declaration in both base and

derived class, that means same name, same return type and same parameter list.

Example of Function Overriding


class Base

public:

void show()

cout << "Base class";

}
};

class Derived:public Base

public:

void show()

cout << "Derived Class";

In this example, function show() is overridden in the derived class. Now let us study how
these overridden functions are called in main() function.

Function Call Binding with class Objects


Connecting the function call to the function body is called Binding. When it is done before
the program is run, its called Early Binding or Static Binding or Compile-time Binding.
class Base

public:

void shaow()

cout << "Base class\t";

};

class Derived:public Base

public:

void show()

cout << "Derived Class";

int main()

Base b; //Base class object

Derived d; //Derived class object


b.show(); //Early Binding Ocuurs

d.show();

Output : Base class Derived class

In the above example, we are calling the overrided function using Base class and Derived
class object. Base class object will call base version of the function and derived class's
object will call the derived version of the function.

Function Call Binding using Base class Pointer


But when we use a Base class's pointer or reference to hold Derived class's object, then
Function call Binding gives some unexpected results.
class Base

public:

void show()

cout << "Base class";

};

class Derived:public Base

public:

void show()

cout << "Derived Class";

int main()

Base* b; //Base class pointer

Derived d; //Derived class object

b = &d;

b->show(); //Early Binding Occurs

Output : Base class


In the above example, although, the object is of Derived class, still Base class's method is
called. This happens due to Early Binding.
Compiler on seeing Base class's pointer, set call to Base class's show() function, without
knowing the actual object type.

Virtual Functions
Virtual Function is a function in base class, which is overrided in the derived class, and which
tells the compiler to perform Late Binding on this function.
Virtual Keyword is used to make a member function of the base class Virtual.

Late Binding
In Late Binding function call is resolved at runtime. Hence, now compiler determines the type
of object at runtime, and then binds the function call. Late Binding is also
called Dynamic Binding or Runtime Binding.

Problem without Virtual Keyword


class Base

public:

void show()

cout << "Base class";

};

class Derived:public Base

public:

void show()

cout << "Derived Class";

int main()

{
Base* b; //Base class pointer

Derived d; //Derived class object

b = &d;

b->show(); //Early Binding Ocuurs

Output : Base class

When we use Base class's pointer to hold Derived class's object, base class pointer or
reference will always call the base version of the function

Using Virtual Keyword


We can make base class's methods virtual by using virtual keyword while declaring them.
Virtual keyword will lead to Late Binding of that method.
class Base

public:

virtual void show()

cout << "Base class";

};

class Derived:public Base

public:

void show()

cout << "Derived Class";

int main()

Base* b; //Base class pointer

Derived d; //Derived class object

b = &d;

b->show(); //Late Binding Ocuurs

}
Output : Derived class

On using Virtual keyword with Base class's function, Late Binding takes place and the
derived version of function will be called, because base class pointer pointes to Derived
class object.

Using Virtual Keyword and Accessing Private Method of Derived class


We can call private function of derived class from the base class pointer with the help of
virtual keyword. Compiler checks for access specifier only at compile time. So at run time
when late binding occurs it does not check whether we are calling the private function or
public function.
#include

using namespace std;

class A

public:

virtual void show()

cout << "Base class\n";

};

class B: public A

private:

virtual void show()

cout << "Derived class\n";

};

int main()

A *a;

B b;

a = &b;

a -> show();
}

Output : Derived class

Mechanism of Late Binding

To accomplich late binding, Compiler creates VTABLEs, for each class with virtual function.
The address of virtual functions is inserted into these tables. Whenever an object of such
class is created the compiler secretly inserts a pointer called vpointer, pointing to VTABLE
for that object. Hence when function is called, compiler is able to resovle the call by binding
the correct function using the vpointer.

Important Points to Remember

1. Only the Base class Method's declaration needs the Virtual Keyword, not the

definition.
2. If a function is declared as virtual in the base class, it will be virtual in all its derived

classes.

3. The address of the virtual Function is placed in the VTABLE and the copiler

uses VPTR(vpointer) to point to the Virtual Function.

You might also like