0% found this document useful (0 votes)
4 views40 pages

Unit4.Notes.OOSD

5th sem unit 4 OOSD notes
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
4 views40 pages

Unit4.Notes.OOSD

5th sem unit 4 OOSD notes
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 40

C++ is a statically typed, compiled, general-purpose, case-sensitive, free-form programming

language that supports procedural, object-oriented, and generic programming.


C++ is regarded as a middle-level language, as it comprises a combination of both high-
level and low-level language features.
C++ was developed by Bjarne Stroustrup starting in 1979 at Bell Labs in Murray Hill, New
Jersey, as an enhancement to the C language and originally named C with Classes but later
it was renamed C++ in 1983.
C++ is a superset of C

Object-Oriented Programming
C++ fully supports object-oriented programming, including the four pillars of object-oriented
development −

 Encapsulation
 Data hiding
 Inheritance
 Polymorphism

C++ Basic Syntax


When we consider a C++ program, it can be defined as a collection of objects that
communicate via invoking each other's methods.
Let us now briefly look into what a class, object, methods, and instant variables mean.
 Object − Objects have states and behaviors. Example: A dog has states - color,
name, breed as well as behaviors - , barking, eating. An object is an instance of a
class.
 Class − A class can be defined as a template/blueprint that describes the
behaviors/states that object of its type support.
 Methods − A method is basically a behavior. A class can contain many methods. It is
in methods where the logics are written, data is manipulated and all the actions are
executed.
 Instance Variables − Each object has its unique set of instance variables. An object's
state is created by the values assigned to these instance variables.

C++ Program Structure


Let us look at a simple code that would print the words Hello World.

#include <iostream>
using namespace std;

// main() is where program execution begins.


int main() {
cout << "Hello World"; // prints Hello World
return 0;
}

There is two ways to compile a program in Turbo C++.


1. Press Alt-F9 (as instructed in the status bar of Turbo C++)
2. Go to Compile tab of Menu bar and press Compile or Build All.

Semicolons and Blocks in C++


In C++, the semicolon is a statement terminator. That is, each individual statement must be
ended with a semicolon. It indicates the end of one logical entity.
For example, following are three different statements −
x = y;
y = y + 1;
add(x, y);
A block is a set of logically connected statements that are surrounded by opening and
closing braces. For example −
{
cout << "Hello World"; // prints Hello World
return 0;
}

C++ Identifiers
A C++ identifier is a name used to identify a variable, function, class, module, or any other
user-defined item.
An identifier starts with a letter A to Z or a to z or an underscore (_) followed by zero or more
letters, underscores, and digits (0 to 9).
Here are some examples of acceptable identifiers −
mohd zara abc move_name a_123
myname50 _temp j a23b9 retVal

C++ Keywords
The following list shows the reserved words in C++. These reserved words may not be used
as constant or variable or any other identifier names.

asm Else new this

auto Enum operator throw


bool Explicit private true

break Export protected try

case Extern public typedef

catch False register typeid

char Float reinterpret_cast typename

class For return union

const Friend short unsigned

const_cast Goto signed using

continue If sizeof virtual

default Inline static void

delete Int static_cast volatile

do Long struct wchar_t

double mutable switch while

dynamic_cast namespace template

Variables are containers for storing data values.

In C++, there are different types of variables (defined with different keywords), for example:

 int - stores integers (whole numbers), without decimals, such as 123 or -123
 double - stores floating point numbers, with decimals, such as 19.99 or -19.99
 char - stores single characters, such as 'a' or 'B'. Char values are surrounded by single quotes
 bool - stores values with two states: true or false

Declaring (Creating) Variables

To create a variable, you must specify the type and assign it a value:

Syntax
type variable = value;
Example

Create a variable called myNum of type int and assign it the value 15:

int myNum = 15;


printf(myNum);

CONSTANT
Constants refer to fixed values that the program may not alter during its execution. These fixed values
are also called literals.
Constants can be of any of the basic data types like an integer constant, a floating constant, a
character constant, or a string literal.

Defining Constants

There are two simple ways in C to define constants −


 Using #define preprocessor.
 Using const keyword.

The #define Preprocessor

Given below is the form to use #define preprocessor to define a constant −


#define identifier value
The following example explains it in detail −

#include <stdio.h>

#define LENGTH 10
#define WIDTH 5

int main() {
int area;

area = LENGTH * WIDTH;


printf("value of area : %d", area);
return 0;
}
When the above code is compiled and executed, it produces the following result −
value of area : 50

The const Keyword

You can use const prefix to declare constants with a specific type as follows −
const type variable = value;
The following example explains it in detail −
#include <stdio.h>

int main() {
const int LENGTH = 10;
const int WIDTH = 5;
int area;

area = LENGTH * WIDTH;


printf("value of area : %d", area);
return 0;
}
When the above code is compiled and executed, it produces the following result −
value of area : 50

Opeartors
An operator is a symbol that tells the compiler to perform specific mathematical or logical functions.
C++ language is rich in built-in operators and provides the following types of operators −

 Arithmetic Operators
 Relational Operators
 Logical Operators
 Bitwise Operators
 Assignment Operators
 Misc Operators

Arithmetic Operators

The following table shows all the arithmetic operators supported by the C language. Assume
variable A holds 10 and variable B holds 20 then −
Show Examples
Operator Description Example

+ Adds two operands. A + B = 30

− Subtracts second operand from the first. A − B = -10

* Multiplies both operands. A * B = 200

/ Divides numerator by de-numerator. B/A=2

% Modulus Operator and remainder of after an integer division. B%A=0

++ Increment operator increases the integer value by one. A++ = 11

-- Decrement operator decreases the integer value by one. A-- = 9

Relational Operators

The following table shows all the relational operators supported by C. Assume variable A holds 10
and variable B holds 20 then −
Show Examples

Operator Description Example

== Checks if the values of two operands are equal or not. If yes, then the (A == B)
condition becomes true. is not
true.

!= Checks if the values of two operands are equal or not. If the values are not (A != B)
equal, then the condition becomes true. is true.

!= Checks if the values of two operands are equal or not. If the values are not (A != B)
equal, then the condition becomes true. is true.

> Checks if the value of left operand is greater than the value of right operand. (A > B)
If yes, then the condition becomes true. is not
true.

< Checks if the value of left operand is less than the value of right operand. If (A < B)
yes, then the condition becomes true. is true.

>= Checks if the value of left operand is greater than or equal to the value of (A >= B)
right operand. If yes, then the condition becomes true. is not
true.

<= Checks if the value of left operand is less than or equal to the value of right (A <= B)
operand. If yes, then the condition becomes true. is true.

Logical Operators

Following table shows all the logical operators supported by C language. Assume variable A holds 1
and variable B holds 0, then −
Show Examples

Operator Description Example

&& Called Logical AND operator. If both the operands are non-zero, then the (A &&
condition becomes true. B) is
false.

|| Called Logical OR Operator. If any of the two operands is non-zero, then (A || B)


the condition becomes true. is true.

! Called Logical NOT Operator. It is used to reverse the logical state of its !(A &&
operand. If a condition is true, then Logical NOT operator will make it B) is
false. true.

Bitwise Operators

Bitwise operator works on bits and perform bit-by-bit operation. The truth tables for &, |, and ^ is as
follows −

p q p&q p|q p^q


0 0 0 0 0

0 1 0 1 1

1 1 1 1 0

1 0 0 1 1

Assignment Operators

The following table lists the assignment operators supported by the C language −
Show Examples

Operator Description Example

= Simple assignment operator. Assigns values from right side operands to C=A+
left side operand B will
assign the
value of
A + B to
C

+= Add AND assignment operator. It adds the right operand to the left C += A is
operand and assign the result to the left operand. equivalent
to C = C
+A

-= Subtract AND assignment operator. It subtracts the right operand from the C -= A is
left operand and assigns the result to the left operand. equivalent
to C = C -
A

*= Multiply AND assignment operator. It multiplies the right operand with the C *= A is
left operand and assigns the result to the left operand. equivalent
to C = C
*A
/= Divide AND assignment operator. It divides the left operand with the right C /= A is
operand and assigns the result to the left operand. equivalent
to C = C /
A

%= Modulus AND assignment operator. It takes modulus using two operands


and assigns the result to the left operand. C %= A
is
equivalent
to C = C
%A

&= Bitwise AND assignment operator. C &= 2 is


same as C
=C&2

^= Bitwise exclusive OR and assignment operator. C ^= 2 is


same as C
=C^2

|= Bitwise inclusive OR and assignment operator. C |= 2 is


same as C
=C|2

Misc Operators ↦ sizeof & ternary

Besides the operators discussed above, there are a few other important operators
including sizeof and ? : supported by the C Language.
Show Examples

Operator Description Example

sizeof() Returns the size of a variable. sizeof(a), where a is integer, will return 4.

& Returns the address of a variable. &a; returns the actual address of the variable.

* Pointer to a variable. *a;


?: If Condition is true ? then value X : otherwise
Conditional Expression.
value Y

Data types are used to tell the variables the type of data it can store. Whenever a variable is defined
in C++, the compiler allocates some memory for that variable based on the data-type with which it is
declared. Every data type requires a different amount of memory.

Data types in C++ is mainly divided into three types:

1. Primitive Data Types: These data types are built-in or predefined data types and can be used
directly by the user to declare variables. example: int, char , float, bool etc. Primitive data types
available in C++ are:
 Integer
 Character
 Boolean
 Floating Point
 Double Floating Point
2. Derived Data Types: The data-types that are derived from the primitive or built-in datatypes are
referred to as Derived Data Types. These can be of four types namely:
 Function
 Array
 Pointer
 Reference
3. Abstract or User-Defined Data Types: These data types are defined by user itself. Like,
defining a class in C++ or a structure. C++ provides the following user-defined datatypes:
 Class
 Structure
 Union
 Enumeration
 Typedef defined DataType

Introduction to Control Statements in C++

Control statements enable us to specify the flow of program control; ie, the
order in which the instructions in a program must be executed.
.
Types of Control Statements in C++
1. Decision making statement
2. Looping statement
3. Jumping statement

The if-else statement is used to carry out a logical test and then take one
actions depending on the outcome of the test (ie, whether the outcome is
true or false).
Syntax:

if (condition)

statements

else

{The following program checks whether the entered number is positive or negative.
#include<iostream.h>

int main( )

int a;
cout<<"n Enter anumber:";

cin>>a;

if(a>0)

cout<< "n The number %d is positive.”;

else

cout<<"n The number %d is negative.";


Nested if and if-else Statements

}
It is also possible to embed or to nest if-else statements one within the other.
Nesting is useful in situations where one of several different courses of action
need to be selected.
return 0;

The general format of a nested if-else statement is:


}
if(condition1)
{
// statement(s);
}
else if(condition2)
{
//statement(s);
}
else if (conditionN)
{
//statement(s);
}
else
{
//statement(s);
}
#include<iostream.h>

int main( )
{
int a, b,c;
a=6,b= 5, c=10;
if(a>b)
{
if(b>c)
{
cout<<"n a is Greatest is: ";
}
else if(c>a)
{
cout<<"n c is Greatest is: ";
}
}
else if(b>c) //outermost if-else block
{
cout<<"n b is Greatest is: ";
}
else
{
cout<< “ c Greatest is: " ;
}
return 0;
}

Selection Statement: the switch-case Statement


A switch statement is used for multiple way selections that will branch into different code segments
based on the value of a variable or expression. This expression or variable must be of integer data
type.

Syntax:

switch (expression)
{
case 1:
code segment1;
break;
case 2:
code segment2;
break;
.
.
.
case N:
code segmentN;
break;
Example: a program to print the day of the week.

default:
#include<iostream.h>
default code segment;
int main( )
}
{

int day;

cout<<"nEnter the number of the day:";

cin>>day;
switch(day)
{
case 1:
cout<<"Sunday
cout<<"Wednesday";
break;
case 5:
cout<<"Thursday";
break;
case 6:
cout<<"Friday";
break;
case 7:
cout<<"Saturday";
break;
default:
cout<<"Invalid choice”;
}
return 0;

What is Loop in C++?


Looping Statements in C++ execute the sequence of statements many
times until the stated condition becomes false. A loop in C++ consists of
two parts, a body of a loop and a control statement.

Types of Loops in C++


1. Entry controlled loop

2. Exit controlled loop

In an entry control loop in C++, a condition is checked before executing the body of a loop. It is
also called as a pre-checking loop.

In an exit controlled loop, a condition is checked after executing the body of a loop. It is also
called as a post-checking loop.

Sample Loop

‘C’ programming language provides us with three types of loop constructs:

1. The while loop

2. The do-while loop

3. The for loop

Sr. Loop
Description
No. Type

While In while loop, a condition is evaluated before processing a body of the loop. If a
1.
Loop condition is true then and only then the body of a loop is executed.

Do-While In a do…while loop, the condition is always executed after the body of a loop. It is
2.
Loop also called an exit-controlled loop.
In a for loop, the initial value is performed only once, then the condition tests and
3. For Loop compares the counter to a fixed value after each iteration, stopping the for loop
when false is returned.
While Loop in C++

Syntax:
while (condition)
{
statements;
}
It is an entry-controlled loop. In while loop, a condition is evaluated before
processing a body of the loop. If a condition is true then and only then the
body of a loop is executed.

Following program illustrates while loop in C programming example:

#include<iostream.h>
#include<conio.h> int main()
{
int num=1; //initializing the variable
while(num<=10) //while loop with condition
{
cout<<num;
num++; //incrementing operation
}
return 0;
}
Output:
1
2
3
4
5
6
7
8
9
10

Do-While loop
A do…while loop in C++ is similar to the while loop except that the condition is
always executed after the body of a loop. It is also called an exit-controlled
loop.

Syntax of do while loop in C++ programming language is as follows:

Syntax
do
{
statements
} while (expression);
The following loop program in C++ illustrates the working of a do-while 2:

#include<iostream.h>
#include<conio.h> int main()
{
int num=1; //initializing the variable
do //do-while loop
{
cout<<2*num;
num++; //incrementing operation
}while(num<=10);
return 0;
}
Output:
2
4
6
8
10
12
14
16
18
For loop
A for loop is a more efficient loop structure in ‘C++’ programming. The general
structure of for loop syntax in C++ is as follows:

Syntax o:
for (initial value; condition; incrementation or decrementation )
{
statements;
}
Following program illustrates the for loop in C++ programming
example:
#include<iostream.h
> int main()
{
int number;
for(number=1;number<=10;number++) //for loop
to print 1-10 numbers
{
cout<<"number”; //to print
the number
}
return 0;
}
Output:
1
2
3
4
5
6
7
8
9
10
.

Break Statement
The break statement is used mainly in in the switch statement. It is also useful
for immediately stopping a loop.

We consider the following program which introduces a break to exit a while


loop:

#include <iostream.h> int main() {


int num = 5;
while (num > 0)
{
if (num == 3)
break;
cout<<" num”;
num--;
}}
Output:
5
4

Continue Statement
When you want to skip to the next iteration but remain in the loop, you should
use the continue statement.

For example:

#include <iostream.h> int main()

{
int nb = 7;
while (nb > 0)
{
nb--;
if (nb == 5)
continue;
cout<<" nb”;
}}
Output:
6
4
3
2
1

So, the value 5 is skipped.

Typecasting is making a variable of one type, such as an int, act like another type, a
char, for one single operation. To typecast something, simply put the type of
variable you want the actual variable to act as inside parentheses in front of the
actual variable. (char)a will make 'a' function as a char.

For example:
1
2 #include <iostream>
3
4 using namespace std;
5
6 int main()
7 {
cout<< (char)65 <<"\n";/
}

Consider a situation, when we have two persons with the same name, Zara, in
the same class. Whenever we need to differentiate them definitely we would
have to use some additional information along with their name, like either the
area, if they live in different area or their mother’s or father’s name, etc.

Same situation can arise in your C++ applications. For example, you might be
writing some code that has a function called xyz() and there is another library
available which is also having same function xyz(). Now the compiler has no
way of knowing which version of xyz() function you are referring to within
your code.

A namespace is designed to overcome this difficulty and is used as additional


information to differentiate similar functions, classes, variables etc. with the
same name available in different libraries.
Using namespace, you can define the context in which names are defined. In
essence, a namespace defines a scope.

Defining a Namespace

A namespace definition begins with the keyword namespace followed by the


namespace name as follows −

namespace namespace_name {
// code declarations
}

To call the namespace use (::) the namespace name as follows −

name::code; // code could be variable or function.

Let us see how namespace scope the entities including variable and
functions –

#include <iostream>

using namespace std;

// first name space


namespace first_space {
void func() {
cout << "Inside first_space" << endl;
}
}

// second name space


namespace second_space {
void func() {
cout << "Inside second_space" << endl;
}
}

int main () {
// Calls function from first name space.
first_space::func();

// Calls function from second name space.


second_space::func();
return 0;
}

If we compile and run above code, this would produce the following result −

Inside first_space
Inside second_space

Enum data type


Enumeration (or enum) is a user defined data type in C. It is mainly used to
assign names to integral constants, the names make a program easy to read and
maintain.
The keyword ‘enum’ is used to declare new enumeration types in C and C++..
enum flag{constant1, constant2, constant3, ....... };

Following is an example of enum declaration


num week{Mon, Tue, Wed, Thur, Fri, Sat, Sun};

int main()
{
enum week day;
day = Wed;
cout<<”day”;
return 0;
}

A function is block of code which is used to perform a particular task, for


example let’s say you are writing a large C++ program and in that program
you want to do a particular task several number of times.

This would make you code simple, readable and reusable.

Syntax of Function

return_type function_name (parameter_list)


{
//C++ Statements
}
A simple function example
#include <iostream>
using namespace std;
/* This function adds two integer values
* and returns the result
*/int
sum(int num1, int num2){
int num3 = num1+num2; return num3;
}

int main(){
//Calling the function
cout<<sum(1,99);
return 0;
}

Types of function
We have two types of function in C++

1) Built-in functions
2) User-defined functions

1) Built-in functions
Built-in functions are also known as library functions. We need not to declare
and define these functions as they are already written in the C++ libraries
such as iostream, cmath etc. We can directly call them when we need.

2) User defined function:

The functions that are defined by user is called user defined function.

A simple function example


#include <iostream>
using namespace std;
/* This function adds two integer values
* and returns the result
*/int
sum(int num1, int num2){
int num3 = num1+num2; return num3;
}

int main(){
//Calling the function
cout<<sum(1,99);
return 0;
}

Default Arguments in C++ Functions


The default arguments are used when you provide no arguments or only few
arguments while calling a function. The default arguments are used during
compilation of program.

Example: Default arguments in C++


#include <iostream>
using namespace std;
int sum(int a, int b=10, int c=20);

int main(){
/* In this case a value is passed as
* 1 and b and c values are taken from
* default arguments.
*/
cout<<sum(1)<<endl;

/* In this case a value is passed as


* 1 and b value as 2, value of c values is
* taken from default arguments.
*/
cout<<sum(1, 2)<<endl;

/* In this case all the three values are


* passed during function call, hence no
* default arguments have been used.
*/
cout<<sum(1, 2, 3)<<endl;
return 0;
}
int sum(int a, int b, int c){
int z;
z = a+b+c;
return z;
}
Output:

31
23
6

Rules of default arguments


If you assign default value to an argument, the subsequent arguments
must have default values assigned to them, else you will get compilation
error.

For example: Lets see some valid and invalid cases.


Valid: Following function declarations are valid –

int sum(int a=10, int b=20, int c=30);


int sum(int a, int b=20, int c=30);
int sum(int a, int b, int c=30);
Invalid: Following function declarations are invalid –

/* Since a has default value assigned, all the


* arguments after a (in this case b and c) must have
* default values assigned
*/
int sum(int a=10, int b, int c=30);

/* Since b has default value assigned, all the


* arguments after b (in this case c) must have
* default values assigned
*/
int sum(int a, int b=20, int c);

/* Since a has default value assigned, all the


* arguments after a (in this case b and c) must have
* default values assigned, b has default value but
* c doesn't have, thats why this is also invalid
*/
int sum(int a=10, int b=20, int c);

Inline Function
C++ inline function is powerful concept that is commonly used with classes. If a function is
inline, the compiler places a copy of the code of that function at each point where the
function is called at compile time.

Following is an example, which makes use of inline function to return max of two
numbers −

#include <iostream>
using namespace std;

inline int Max(int x, int y) {


return (x > y)? x : y;
}

// Main function for the program


int main() {
cout << "Max (20,10): " << Max(20,10) << endl;
cout << "Max (0,200): " << Max(0,200) << endl;
cout << "Max (100,1010): " << Max(100,1010) << endl;

return 0;
}
When the above code is compiled and executed, it produces the following result −
Max (20,10): 20
Max (0,200): 200
Max (100,1010): 1010

Call by value and call by reference in C++


There are two ways to pass value or data to function in C++ language: call by value
and call by reference. Original value is not modified in call by value but it is modified
in call by reference.

Let's understand call by value and call by reference in C++ language one by one.
Call by value in C++
In call by value, original value is not modified.

Copy of the argument is passed to the calling function.

Let's try to understand the concept of call by value in C++ language by the example
given below:

1. #include <iostream>
2. using namespace std;
3. void change(int data);
4. int main()
5. {
6. int data = 3;
7. change(data);
8. cout << "Value of the data is: " << data<< endl;
9. return 0;
10. }
11. void change(int data)
12. {
13. data = 5;
14. }

Output:

Value of the data is: 3

Call by reference in C++


In call by reference, original value is modified because we pass reference (address).

Here, address of the value is passed in the function, so actual and formal arguments
share the same address space. Hence, value changed inside the function, is reflected
inside as well as outside the function.

Note: To understand the call by reference, you must have the basic knowledge of
pointers.
Let's try to understand the concept of call by reference in C++ language by the
example given below:

1. #include<iostream>
2. using namespace std;
3. void swap(int *x, int *y)
4. {
5. int swap;
6. swap=*x;
7. *x=*y;
8. *y=swap;
9. }
10. int main()
11. {
12. int x=500, y=100;
13. swap(&x, &y); // passing value to function
14. cout<<"Value of x is: "<<x<<endl;
15. cout<<"Value of y is: "<<y<<endl;
16. return 0;
17. }

Output:

Value of x is: 100


Value of y is: 500

Difference between call by value and call by


reference in C++

No. Call by value Call by reference

1 A copy of value is passed to the An address of value is passed to the


function function

2 Changes made inside the function is Changes made inside the function is
not reflected on other functions reflected outside the function also
3 Actual and formal arguments will be Actual and formal arguments will be
created in different memory location created in same memory location

Difference between Inline and Macro in C++ :


S.NO Inline Macro

An inline function is defined by Whereas the macros are defined


1. the inline keyword. by the #define keyword.

Through inline function, the


class’s data members can be Whereas macro can’t access the
2. accessed. class’s data members.

In the case of inline function, Whereas in the case of macros,


the program can be easily the program can’t be easily
3. debugged. debugged.

Whereas in the case of macro, the


In the case of inline, the arguments are evaluated every
arguments are evaluated only time whenever macro is used in
4. once. the program.

In C++, inline may be defined Whereas the macro is all the time
either inside the class or defined at the beginning of the
5. outside the class. program.

In C++, inside the class, the


short length functions are
automatically made the inline While the macro is specifically
6. functions. defined.

Inline is not as widely used as


7. macros. While the macro is widely used.

Inline is not used in While the macro is very much used


8. competitive programming. in competitive programming.

While the macro is not terminated


Inline function is terminated by by any symbol, it is terminated by a
9. the curly brace at the end. new line.

Function Overloading in C++


Function overloading is a feature of object oriented programming where two
or more functions can have the same name but different parameters.
When a function name is overloaded with different jobs it is called Function
Overloading.
In Function Overloading “Function” name should be the same and the
arguments should be different.
Function overloading can be considered as an example of polymorphism
feature in C++.
Following is a simple C++ example to demonstrate function overloading.

#include <iostream>

using namespace std;

void print(int i) {

cout << " Here is int " << i << endl;

void print(double f) {

cout << " Here is float " << f << endl;

void print(char const *c) {

cout << " Here is char* " << c << endl;

int main() {

print(10);
print(10.10);

print("ten");

return 0;

Output:
Here is int 10
Here is float 10.1
Here is char* ten

Virtual Function in C++


A virtual function is a member function which is declared within a base class
and is re-defined(Overridden) by a derived class. When you refer to a
derived class object using a pointer or a reference to the base class, you can
call a virtual function for that object and execute the derived class’s version
of the function.
 Virtual functions ensure that the correct function is called for an object,
regardless of the type of reference (or pointer) used for function call.
 They are mainly used to achieve Runtime polymorphism
 Functions are declared with a virtual keyword in base class.
 The resolving of function call is done at Run-time.

Rules for Virtual Functions


1. Virtual functions cannot be static.
2. A virtual function can be a friend function of another class.
3. Virtual functions should be accessed using pointer or reference of base
class type to achieve run time polymorphism.
4. The prototype of virtual functions should be the same in the base as well
as derived class.
5. They are always defined in the base class and overridden in a derived
class. It is not mandatory for the derived class to override (or re-define the
virtual function), in that case, the base class version of the function is
used.
6. A class may have virtual destructor but it cannot have a virtual
constructor.

You might also like