0% found this document useful (0 votes)
371 views

Oop Ioe Notes Chapter Wise

The document provides an introduction to object oriented programming (OOP) and C++. It discusses the limitations of procedural programming and how OOP addresses these limitations through concepts like classes, objects, encapsulation, inheritance and polymorphism. It then gives an overview of C++, highlighting its features like classes, derived classes, access control, constructors/destructors, and function/operator overloading. The document compares procedural programming with OOP and lists some advantages and disadvantages of OOP. It also provides a brief history of C++.

Uploaded by

Movie Masala
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
371 views

Oop Ioe Notes Chapter Wise

The document provides an introduction to object oriented programming (OOP) and C++. It discusses the limitations of procedural programming and how OOP addresses these limitations through concepts like classes, objects, encapsulation, inheritance and polymorphism. It then gives an overview of C++, highlighting its features like classes, derived classes, access control, constructors/destructors, and function/operator overloading. The document compares procedural programming with OOP and lists some advantages and disadvantages of OOP. It also provides a brief history of C++.

Uploaded by

Movie Masala
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 61

1.

Introduction to Object Oriented Programming


Issues with Procedural Programming
- In procedure oriented approach, the problem is analyzed and as a sequence of things to be done like reading, calculating
and displaying for which functions are used.
- Some common POP programming languages are COBOL, C, FORTRAN and so on.

Characteristics of POP
1. Emphasis is on algorithms
2. Follows top to bottom approach
3. Coding of large program is done by dividing it into smaller modules called functions
4. Global data can be shared by any functions
5. Functions are capable of transferring data from one form to another

Limitations of POP
1. Functions are emphasized rather than data.
2. Global data are vulnerable to an inadvertent change by a functions
3. Difficulty in recognizing which function uses which global data
4. Modification in global data also requires modification in functions using it
5. Function are action oriented so can not correspond to elements of the problem. So, it does not model the real world
problems.

Basic OOP

- In other to solve the limitations of the POP, the concept of OOP arises.
- In OOP, emphasis is given to data because of which data are protected from being accidental modification or data
corruption.
- Large problem is divided into objects and then build data and function around them.

Features of OOP
1. Emphasis is given on data rather than procedures.
2. Programs are divided into objects.
3. Function and data are tied together in a single unit.
4. Data can be hidden to prevent from accidental alteration from other functions.
5. Data access is done through the visible function.
6. Objects can communicate with each other through functions.
7. Follows bottom up approach.

Procedure Oriented vs Object Oriented Programming

Procedure oriented Object oriented


1. Emphasis is given on procedure. 1. Emphasis is given on data.
2. Programs are divided into functions. 2. Programs are divided into objects.
3. Data can not be hidden. 3. Data can be hidden.
4. It does not model the real world problems. 4. It models the real world problems.
5. Data moves from function to function. 5. Data and function are tied together.
6. Maintaining and enhancing code is still difficult. 6. Maintaining and enhancing code is easy.
7. Code reusability is difficult. 7. Code reusability is easy.
8. Follows top-down approach. 8. Follows bottom-up approach.
9. Eg: COBOL, C 9. Eg: JAVA, C++

Concept of Object Oriented Programming

1. Object:
- Objects are the basic run time entities in an object oriented system.
- They represent any item that the program can handle.
- The objects are so chosen to match with the real world objects.
- When a program is executed, the objects interact by sending messages to one another.
- Eg: Consider an object ‘student’ with data (name, roll, mark) and functions {total(), average(), display()}

2. Class:
- Class is the user defined data type used to declare the object.
- It is possible to declare any number of objects belonging to that class.
- Each object of a class is associated with the data of that class.
- Eg: To create an object mango belonging to the class fruit;
fruit mango;

3. Abstraction:
- Abstraction is the act of representing the essential features without including the background details or explanations.
- Classes are the concept of abstraction. So, class is a abstract data type.
- It can manage the program complexity.

4. Encapsulation:
- Encapsulation is the mechanism of combining data function together into a single unit.
- It prevents the data being accessed by other code.

5. Inheritance:
- Inheritance is the process of creating new classes based on the existing class such that new class acquires features from the
existing class and adds more features on it.
- The process of deriving a new class from the existing base class is called inheritance.

6. Polymorphism:
- Polymorphism is the ability to take more than one form depending on what they are operating on.
- It allows different objects to respond to the same operation in different ways, the response being specific to the type of
object.
- Eg: operator overloading, function overloading and so on.
Example of Some Object Oriented Languages

1. Small talk
2. Eiffel
3. JAVA
4. C#
5. D
6. C++

Advantages and Disadvantages of OOP

Advantages of OOP
1. Data hiding ensures program security.
2. Software development becomes easy as programs are divided into objects.
3. Proper management of software complexity.
4. Ensure real world problems modeling.
5. Easy to reuse codes.
6. Techniques like inheritance and templates eliminates redundant code.

Disadvantages of OOP
1. Requires more compilation time.
2. Difficult to trace and debug errors in complex program.
3. No benefits in short run of programs.

2. Introduction to C++
Need of C++
- It is very difficult to apply structured programming language like C to solve the complex problem and model the real world
problems perfectly.
- To overcome such complexity, the programmers find the need of C++ and then C++ was developed.

Features of C++

1. Namespace
It is used for logical grouping of program elements. It helps to develop large application by different members of the team
independently without conflict of identifiers name.

2. Class
It is user defined data types that combines data and function together.

3. Derived class
It is new class formed from existing classes which ensures code reuasbility.
4. Access controller
Private, public and protected keywords control the access of members within the class.

5. Constructor and Destructor


A constructor is used to allocate required memory for members and initialize the objects of its class. It has the same name as
of its class.
A destructor complements the operation of constructor. It has same name as of its class but preceded by tilde (~) symbol.

6. Friend function and class


Friend function is used to access even the private members of a class. In other to access hidden members of a class, by
another class, the class must be declared as friend class.

7. Reference variable
It is useful to pass arguments by reference.

8. Function Overloading
When same function name is used for different operation, it is called function overloading. It is used to manipulate same
nature of problems but with different numbers of arguments.

9. Default argument
Default argument come into action when no any arguments are passed during a function call.

10. Inline function


The function body put directly in the called location to reduce execution time.

11. Operator overloading


It extends the meaning of an operator for user defined type.

12. Easier memory management


C++ provides 'new' operator for dynamic memory allocation and 'delete' operator for dynamic memory deallocation.
13. Stream class library
Header files declare stream class, functions and declarations.

14. Run time polymorphism


The member function of a class can be selected at run time.

15. Exception handling


Exception are the errors during run time.

16. Run time type information (RTTI)


It is mechanism that allows the type of an object to be determined during program execution. The elements of RTTI are
dynamic_cast, type id operator and type_info class.

C++ vs C

C C++
1. It was introduced by Dennis Ritchie at AT and T Bell lab.
1. It was introduced by Bjarne Stroupstup at AT and T Bell lab.
2. It follows procedural approach of programming
2. It follows object oriented approach.
paradigm.
3. Languages such as JAVA, object oriented PHP are influenced by C++.
3. Languages such as C++, perl, PHP are influenced by C.
4. C++ program is comparatively slower to compile.
4. C program is faster to compile.
5. It supports extension like operator overloading, inheritance and so on.
5. It does not support extension in programming.
6. It provides improved and extended libraries.
6. It provides fewer libraries.
7. It provides more keywords.
7. It provides fewer keywords.

History of C++

- In 1967, Simula and BCPL


- In 1978, B; then K and RC; then Classic C
- In 1980, C with classes
- In 1985, Early C++ , C89
- In 1989, ARM C++
- In 1998, C++ 98, C99

3. C++ Language Constructs


C++ Program Structure
- A typical C++ program has a structure as shown below:
----------------------------------
| |
| Header Files |
| Class Declaration |
| Member Function Definition |
| Main Function |
| |
----------------------------------

Example

#include //Header Files


using namespace std;

class employee //Class declaration with class name employee


{
char name[30]; //Class data initialization
int age;
public:
void getdata(); // Member function definition
void display();
};

void employee : getdata() //Function Definition


{
cout << "Enter the name and age :: ";
cin >> name >> age;
}

void employee : display()


{
cout << "Name = " << name <<"\n Age = " << age;
}

int main() //Main Function


{
employee e;
e.getdata();
e.display();
return 0;
}

Character Set and Tokens

Character Set
- Character set is the any acceptable alphabet, digit, symbol, etc that represent information in a program which together
forms tokens.
- The valid character set of C++ are:
1. Alphabets (a - z, A - Z)
2. Digits (0 - 9)
3. Special Symbols (+, -, *, /, =, {, }, etc)
4. White space (blank, new line, tab, etc)

Tokens
- Tokens are the smallest individual units of a program formed by the combination of character sets.
- The tokens in C++ are:
1. Keyword
2. Identifier
3. Constant
4. Operator
5. Punctuation

Keyword
- Keywords are the reserved words in C++ that have some special functioning.
- They can not be defined by user for any other purposes.
- They should be in lower case letters.
- Eg: int, auto, private, default, char, switch, if, for, etc.

Identifier
- Identifiers are the name of variables, function, array, class and so on created by the users.
- The rules for naming identifiers are as follows:
1. Only alphabets, digits and underscore are permitted.
2. Name can not start with digits.
3. Uppercase and lowercase letters are distinct.
4. Keywords can not be used.
5. No limits on the length of the name.

Constants / Literals
- Constants represent the fixed values that can not be altered during the program execution.
- It is classified as:
1. String constant
2. Numeric constant
3. Character constant
- Numeric constants are further divided into:
1. Integer
2. Float
3. Octal
4. Hex

Operator
- Operators are the special symbols used to perform mathematical or logical operations.
- The various operators used are as follows:
1. Arithmetic (+, -, *, /, %)
2. Assignment (=)
3. Self Assignment (++, --)
4. Arithmetic Assignment (+= , -=, *=, /=, %=)
5. Relational (>, <, >=, <=)
6. Equality (==, !=)
7. Logical (&&, ||, !)
8. Bitwise (>>, <<, ~, ^, |)
9. Other (?, :, ::, ( ), [ ], ->, etc)

Punctuator
- They are the special symbols which act as a punctuation marks.
- Eg: Parenthesis ( ), Braces { }, Comma ',', Semicolon :

Precedence and Associativity

Precedence Operators Associativity


------------------------------------------------------------------------------------------------------
1 (), [ ], ->, ., postfix (++, --) Left to right
2 ++, --, !, ~, size of(), unary(+, -), & Right to left
3 *, /, % Left to right
4 +, - Left to right
5 <<, >> Left to right
6 <, <=, >, >= Left to right
7 ==, != Left to right
8 & Left to right
9 ^ Left to right
10 | Left to right
11 && Left to right
12 || Left to right
13 ?: Right to left
14 Assignment Right to left
15 , Left to right

Variable Declaration and Expression

- Variables are the entities that holds values which may alter during the program execution.
- Every variable must be declared.

Syntax:
data_type variable_name_1, variable_name_2, ..............., variable_name_n;

- Expressions are the combination of variable, constant, function call, operators and so on.
- Eg: x = a + b

Statements and Data Types

Statement
- A statement carries out some action.
- Expression statement consists of any valid C++ expressions followed by a semicolon.
Eg: x = a + b;
- Compound statement is a group of C++ expression written wihin { and }.

Example:
{
a = b + c;
x = y;
}

- Control statement is used to control the flow of program under the given conditions.

Example:
if (a > b)
{

Data Type
- A data type defines a set of values that a variable can store and a set of operations that can be performed on that variable.
- It is of two types: Basic and Derived data types.
- Basic data types includes:
1. char
2. int
3. float, double
4. bool
- Derived data types includes:
1. array
2. structure
3. union
4. class
5. pointer
6. reference

Type Conversion and Promotion Rules

- Type conversion is the process of conversion of one data type into another type.
- It is of two types:
1. Implicit conversion
2. Explicit conversion

Implicit Conversion
- While evaluating expression containing mixed data types, one data type is automatically converted to higher type.
- The basic rule is:
char --> short --> int --> long --> float --> double --> long double
Explicit Conversion
- It is done by programmers as per their needs.
- The basic syntax is:
(data_type) expression;
- Eg:
int x;
(float) x;``

Preprocessor Directives

- The line beginning with # sign are called preprocessor directives.


- Eg:
#include
#define N 100

Namespace

- Namespace is the process of logically grouping of program elements.


- It is used to localize the name of identifiers to remove naming conflicts across different modules designed by different
programmers.

Syntax:
namespace namespace_name
{
//Declarations of variables, classes, functions
}

- In other to include the already defined namespace into our scope, keyword 'using' is added.
- Syntax : using namespace namespace_name

User Defined Constant

- The keyword 'const' added before variable declaration indicates that the variable value does not alter during program
execution.

Example:
const float pi = 3.17
const int max = 255

Input/Output Streams and Manipulators


Input/Output Stream
-Stream is a sequence of characters from source to destination.
- Output stream is a sequence of characters from computer to output device.
- Input stream is a sequence of characters from input device to computer.
- 'cout' is used for output and 'cin' for input.

#include
int main()
{
char name[30];
int age;
cout << "Enter name and age:";
cin >> name >> age;
cout << "Name = " << name << "Age = " << age;
return 0;
}

Manipulators
- Manipulators are instruction to i/o stream that modify the output in various ways.
- The header file must be included to use manipulators.

endl Manipulator
- It causes a line feed to be inserted into the stream so that the subsequent text is displayed on new line.
- Eg: cout << "Subject : C++";
cout << endl << "Total :" << marks;

setw Manipulator
- It causes the number or string that follows it in the stream to be printed within a field specified in the argument.
- Syntax : cout << setw(n) << variable_name;

C++ Example using Manipulators

#include //Header Files


#include

int main()
{
float mark1 = 99, mark2 = 74;
cout << setw(5) << "Names" << setw(7) << "Marks" << endl;
cout << setw(5) << "Suraj" << setw(7) << mark1 << endl;
cout << setw(5) << "Anil" << setw(7) << mark2 << endl;
return 0;
}
Output:
Names Marks
Suraj 99
Anil 74

DMA with new and delete

Dynamic Memory Allocation


- It is the process of allocating memory during run time as per the need.
- 'new' operator is used for allocation and 'delete' operator is used for deallocation.

New
- It obtains memory at run time from memory heap of operating system and returns the address of obtained memory.
- Syntax:
data_type *data_type_pointer;
data_type_pointer = new data_type; //Allocate for single variable
data_type_pointer = new data_type[size]; //Allocate an array

Delete
- It releases the memory allocated by 'new' back to operating system memory heap.
- Syntax:
delete data_type_ptr;
delete [ ] data_type_ptr;

Illustration of DMA in C++

#include //Header Files

int main()
{
int n, i, *arr, tot=0;
float avg;
cout << "How many numbers:";
cin >> n;
arr = new int[n];
cout << "Enter elements";
for (i = 0; i < n; i++)
{
cin >> arr[i];
tot += arr[i];
}
avg = tot / n;
cout << endl << "Total = " << tot;
cout << endl << "Average = " << avg;
delete []arr;
return 0;
}

Condition and Looping

1. Sequential
2. Selective (if, if_else, switch, ?:)
3. Repetitive (while, do_while, for)

Syntax:
if statement

if (test_exp)
statement;

if_else statement

if (test_exp)
statement1;
else
statement2;

nested if_else

if (exp1)
if (exp2)
statement 1;
else
statement 2;
else
statement3;

switch statement

switch (exp)
{
case val_1:
statement1;
break;
case val_2:
statement2;
break;
..........
..........
default:
default_statement;
}

Conditional operator

exp1 ? true_statement : false_statement;

while loop

while (test_exp)
statement;

do_while loop

do
{
statement;
} while (test_exp);

for loop

for (initialize; test_exp; exp3)


statement;

Functions

- Functions is a group of statements in a single unit to perform some specific task.


- It helps in code reusability.

Function Prototype
- A function header specified before function call.
- Syntax:
return_type function_name (parameter_list);

Function Definition

Syntax:

return_type function_name (parameter_list)


{
//body of function
}
Function Call
- Syntax:
function_name (argument_list);

Illustration of Function in C++

#include //Header Files

float calc(int, int, float); //Function prototype

int main()
{
int p, t;
float r, i;
cout << "Enter the value for p, t and r :";
cin >> p >> t >> r;
i = calc(p, t, r); //Function call
cout << "The interest is : " << i;
return 0;
}

//Function Definition
float calc(int p, int t, float r)
{
return (p * t * r / 100);
}

Function Overloading
- It is a logical method of calling several functions with different arguments and data types which performs identical actions
by the same function name.
- Eg:
void display(); //No argument
void display(int); //one int argument
void display(int, char); //one int and one char argument
- The advantages of function overloading are as follows:
1. Eliminates the use of different function name for same operation.
2. Easy to understand and debug.
3. Easy to maintain code.
4. Better real world problem analysis.
- It is categorized as:
1. type of argument
2. number of argument
3. type and number of arguments
Type of Argument:
#include //Header Files

void display(char);
void display(int);

int main()
{
char ch = 's';
int num = 20;
cout << "Character : ";
display(ch);
cout << "Integer : ";
display(num);
return 0;
}

void display(char c)
{
cout << c;
}

void display(int n)
{
cout << n;
}

Number of Argument:

#include //Header Files

void display(int);
void display(int, int);

int main()
{
int ch = 10;
int num = 20;
cout << "One argument : ";
display(ch);
cout << "Two argument : ";
display(ch, num);
return 0;
}

void display(int c)
{
cout << c;
}
void display(int c, int n)
{
cout << c << n;
}

Type and Number of Arguments:

#include //Header Files

void display(int);
void display(char, int);

int main()
{
int ch = 's';
int num = 20;
cout << "One argument of integer type : ";
display(num);
cout << "Two argument of integer and character type: ";
display(ch, num);
return 0;
}

void display(int c)
{
cout << c;
}

void display(char c, int n)


{
cout << c << n;
}

Inline Function
- The function in which the code is copied in the called location is known as inline function.
- Syntax : inline return_type function_name (parameters)
- In ordinary function, when function is called, the control is passed to the calling function and after execution of the
function, the control is passed back to the called function.
- In case of inline function, on function call, the code of called function is copied at the place of the call and compiled at the
calling function without flow of control from calling to called function and back to calling function.
- This helps to minimize the execution time.

#include //Header Files

inline void display(int c)


{
cout << c;
}
int main()
{
int num = 20;
cout << "Inline function output : ";
display(num);
return 0;
}

Default Argument
- During function call, less number of arguments can be passed than the actual number of arguments needed.
- This mechanism is possible by providing default argument.
- It helps in easy development and maintenance of the code.

#include //Header Files

inline void display(int c = 10, int d = 20)


{
int total;
total = c + d;
cout << total;
}

int main()
{
display(); //Total = 30
display(30); //Total = 30 + 20 = 50
display(5, 5); //Total = 5 + 5 = 10
return 0;
}

Pass by Reference
- On passing arguments by reference, the formal arguments in called function became aliases to actual arguments in the
calling function.
- It is necessary when changes in called function is also important for the original arguments.

#include

void swap(int&, int&);

int main()
{
int a = 4, b = 6;
cout << "Before swapping" << a << "and" << b;
swap(a, b);
cout << "After swapping" << a << "and" << b;
return 0;
}

void swap(int &x, int &y)


{
int temp;
temp = x;
x = y;
y = temp;
}

Return by Reference
- A function is able to return a variable by reference.

#include

int& max(int &x, int &y)


{
if (x > y)
return x;
else
return y;
}

int main()
{
int a = 5, b = 10;
c = max(a, b);
cout << c;
return 0;
}

Array, Pointer and String

Array
- It is a collection of similar data items.
- Each data item is called an element.
- Index starts with 0.
- 1D array declaration : type array_name[no_of_element];
- 2D array declaration : type array_name[row] [column];

Pointer
- It is a variable containing address of another variable.
- It is useful to return more than one value from the called function.
- It creates complex data structures.
- It is declared as:
data_type *variable_name;
- Eg: int *pnum;

String
- It is an array of characters.
- It is terminated by null character.
- It is declared as:
char string_name[no_of_characters];

Structure, Union and Enumeration

Structure
- It is the method of combining different data types.
- After defining a structure, a variable of its type can be declared.

Example:
struct sudent
{
char name[30];
int age;
};
student s1;

OR,

struct sudent
{
char name[30];
int age;
} s1;

Union
- It is similar to structure but differs in the way of storing and retrieving data.
- Union holds only one value for one data type.
- If a new assignment is done, the previous one is erased automatically.

Example:
Union name {
data_type mem1;
data_type mem2;
};
Enumeration
- Set of values represented by identifiers called enumeration constant.

Syntax:
enum name {
mem1;
mem2;
........
mem n;
};

Declaration:
enum name var1, var2, var3, ................ , varn;

4. Objects and Classes


C++ Classes
- Class binds the data and its associated functions together.
- It allows data hiding from external use.
- The general form of class declaration is:

class class_name
{
private:
data_type data1;
.........
public:
return_type function_name(data_type arg_list);
.............
};

Access Specifiers

- There are 3 access specifiers : private, public and protected.


- It determines the visibility level of class members.
- Members declared as private can be accessed only from within the class.
- Public members are visible from outside the class also.
- Protected members are visible by member function and friend function.
- By default, the members of a class are private.
- Variables declared inside a class is data members.
- Functions declared inside a class is member functions.

Object and Member Access

- Once a class has been declared, it is possible to create variables of its type, known as objects of a class.
- Syntax : class_name obj_name1, obj_name2, .........;
- The necessary memory space is allocated when object is created.
- The public members of a class can be accessed by making use of member access operator or dot operator i.e '.'
- Syntax:
class_object . data_member;
class_object . member_function (actual_arguments);

Defining Member Functions

- The member functions can be defined inside or outside the class definition.

Inside Class Definition


- The functions defined inside the class is treated as inline function.

#include

class employee
{
char name[30];
float salary;
public:
void getdata()
{
cout << "Enter name and salary : ";
cin >> name >> salary;
}
void showdata()
{
cout << name << salary << endl;
}
};

int main()
{
employee *eptr;
employee e;
eptr = &e;

eptr -> getdata();


eptr -> showdata();
return 0;
}

Outside Class Definition


- The function declaration must be inside the class definition.
- The function defined outside the class should be bound with the class to which it belongs by the use of scope resolution
operator '::'
#include

class employee
{
char name[30];
float salary;
public:
void getdata();
void showdata();
};

void employee :: getdata()


{
cout << "Enter name and salary : ";
cin >> name >> salary;
}

void employee :: showdata()


{
cout << name << salary << endl;
}

int main()
{
employee *eptr;
employee e;
eptr = &e;

eptr -> getdata();


eptr -> showdata();
return 0;
}

Constructors

Constructor
- Constructor is a special member function which is automatically called during object creation.
- Its name is same as the name of the class.
- It has no return value specification.

Default Constructor and Parameterized Constructor


- Default constructor takes no arguments.
- It is automatically called when no arguments are supplied.
- Parameterized constructor is the constructor with parameters.
Illustration of default and parameterized constructors

class counter
{
private:
int count;
public:
// Default Constructor
counter()
{
count = 0;
}

// Parameterized Constructor
counter(int n)
{
count = n;
}
.............
.............
};

int main()
{
counter c1;
counter c2(5);
}

Copy Constructor
- It declares and initializes an object from another object of its own class.
- When no copy constructor is defined, the compiler supplies its own copy constructor known as default constructor.

Illustration of Copy constructor

class code
{
int id;
public:
code() {} // Default constructor
code (int a) // Parameterized constructor
{
id = a;
}
code(code &a) //Copy constructor
{
id = a.id;
}
void display()
{
cout << id;
}
};
int main()
{
code a(100);
code b(a); //Calling copy constructor
code c = a; //Calling copy constructor
a.display();
b.display();
c.display();
return 0;
}

Destructors

- It is a member function whose name is same as the class name but is preceded by a tide (~).
- It is invoked when an object is destroyed.
- It never takes any argument nor any return value.

class test
{
private:
...........
public:
test() { } //Constructor
~test() { } //Destructor
};

Object as Function Argument and Return Type

Object as Function Arguments


- The objects can be passed to the function as an arguments.

#include

class complex
{
float real, img;
public:
void getdata()
{
cout << "Enter real and imaginary part";
cin >> real >> img;
}
void showdata()
{
cout << real << "+i" << img;
}
void add(complex c1, complex c2)
{
real = c1.real + c2.real;
img = c2.img + c2.img;
}
};

int main()
{
complex c1, c2, c3;
c1.getdata();
c2.getdata();
c3.add(c1, c2);
c1.showdata();
c2.showdata();
c3.showdata();
return 0;
}

Object as Return Type

#include

class complex
{
float real, img;
public:
void getdata()
{
cout << "Enter real and imaginary part";
cin >> real >> img;
}
void showdata()
{
cout << real << "+i" << img;
}
complex add(complex c2)
{
complex result;
result.real = real + c2.real;
result.img = img + c2.img;
return result;
}
};

int main()
{
complex c1, c2, c3;
c1.getdata();
c2.getdata();
c3 = c1.add(c2);
c1.showdata();
c2.showdata();
c3.showdata();
return 0;
}
Array of Objects

class employee
{
private:
int emp_id;
char name[30];
public:
void getdata();
void showdata();
};

//Declaring array of objects


employee emp[50];

Pointer to Objects and Member Access

- The object pointer variable holds the address of the objects.


- The starting address of an object can be achieved by address operator.
- The declaration of pointer to object is:

class_name *pointer_to_object;
class_name object_name;
pointer_to_object = &object_name;

- The members can be accessed as:


pointer_to_object -> member;
OR,
(*pointer_to_object).member;

Illustration of Pointers in C++

#include

class employee
{
char name[30];
float salary;
public:
void getdata()
{
cout << "Enter name and salary : ";
cin >> name >> salary;
}
void showdata()
{
cout << name << salary << endl;
}
};

int main()
{
employee *eptr;
employee e;
eptr = &e;

eptr -> getdata();


eptr -> showdata();
return 0;
}

DMA for Objects and Object Array

Syntax
class_name *obj_ptr;
obj_ptr = new class_name; //Dynamic allocation for object
obj_ptr = new class_name[size]; //Dynamic allocation for object array

Illustration of DMA in C++

class test
{
private:
int data;
...........
public:
test() { }
test(int a) { data = a; }
};

test *tptr, *taptr;


tptr = new test;
taptr = new test[a];

this Pointer

- Every non-static member function of object have access to 'this' pointer, which points to the object itself.
- It is defined implicitly.
- Any non-static function can find out the address of the object of which it is a member of.
Illustration of 'this' pointer

class counter
{
unsigned int count;
public:
counter()
{
count = 0;
}
counter(int n)
{
count = n;
}
counter operator ++()
{
++count;
return *this;
}
};

Static Data Member and Static Function

Static Data Member


- Storage space for static data members are not allocated when the object is created.
- Static data members of all objects are stored in the same memory locations.
- It is declared in the class and is defined outside the class.
- It is declared by using keyword 'static'.

Illustration of Static Data

#include

class item
{
static int count; //Static Data Member Declaration
int number;
public:
void getdata(int a)
{
number = a;
count++;
}
void getcount()
{
cout << "Count = " << count;
}
};
int item :: count = 0; //Static Data Definition

int main()
{
item a, b;
a.getcount();
b.getcount();
a.getdata(100);
b.getdata(200);
a.getcount();
b.getcount();
return 0;
}

Output:
count = 0
count = 0
count = 2
count = 2

Static Function
- It belongs to a class not to any object.
- It can access only the static data members.

Illustration of Static Function

#include

class item
{
int code;
static int count;
public:
void setcode()
{
code = ++count * 10;
}
void showcode()
{
cout << code;
}
static void showcount() //Static Function Definition
{
count << count;
}
};

int item :: count = 0; //Static Data Definition


int main()
{
item t1, t2;
t1.setcode();
t2.setcode();
test :: showcount(); // Calling static function
return 0;
}

Constant Member Function and Constant Objects

Constant Data Member


- The value of constant data members can not be changed by any function members.
- Initialization can be done only by the constructors.

Illustration of Constant Data Member

#include

class con
{
const int constdata; //Declaration of constant data member
public:
con() : constdata(0) {} //Definition of constant data through constructor
void display();
};

void con :: display()


{
cout << constdata <<endl;
}
</endl;

Constant Member Function


- The functions which guarantee not to change object's value are called constant functions.
- Constant objects can only call constant functions.

Illustration of Constant Member Function

class time
{
private:
int hr, min, sec;
public:
time(int h = 0, int m = 0, int s = 0)
{
hr = h;
min = m;
sec = s;
}
int hour() const //Definition for constant functions
{
return hr;
}
int minute() const
{
return min;
}
int second() const
{
return sec;
}
};

Friend Function and Friend Class

Friend Function
- Using friend function, non-member of a class can access the member of a class.
- A friend function is not a member of any classes but has the full access to the member of class where it is declared as
friend.
- It can be invoked like a normal function without help of any object.
- It can not access member name directly and has to use an object name and dot operator with each member name.
- It takes object as arguments.

Illustration of Friend Function

#include

class complex
{
private:
float real, img;
friend complex add(complex, complex); //Friend function declaration
public:
void getvalue()
{
cout << "Enter real and imaginary part : ";
cin >> real >> img;
}
void showvalue()
{
cout << real << " + i" << img;
}
};

complex add(complex c1, complex c2)


{
complex temp;
temp.real = c1.real + c2.real;
temp.img = c1.img + c2.img;
return temp;
}

int main()
{
complex c1, c2, c3;
c1.getvalue();
c2.getvalue();
c3 = add(c1, c2);
c3.showvalue();
return 0;
}

Friend Class
- Any function that is a member of another class can also be a friend of one class.

Illustration of Friend Class

#include

class B;

class A
{
char passA[20];
public:
void getdata()
{
cout << "Enter password of A : ";
cin >> passA;
}
void showdata(B);
friend class B;
};

class B
{
char passB[20];
public:
void getdata()
{
cout << "Enter password of B : ";
cin >> passB;
}
void showdata(A a)
{
cout << "Password of A is : " << a.passA;
}
friend class A;
};

void A :: showdata(B b)
{
cout << "Password of B is : " << b.passB;
}

int main()
{
A a;
B b;
a.getdata();
b.getdata();
a.showdata(b);
b.showdata(a);
return 0;
}

5. Operator Overloading
Overridable Operators
- It is the mechanism of adding special meaning to an operator.
- It provides flexible option for extension of the meaning of the operator when applied to user defined data types.
- All operators are not overloadable.
- The operator that can be overloaded are as follows:
1. Member access operator (.)
2. Pointer to member access operator (.*)
3. Scope resolution operator (::)
4. Size of operator
5. Conditional operator (?:)
6. Runtime type information operator (typeid)
- All other operators can be overloaded.

Syntax of Operator Overloading

- Operator function must be defined.


- Operator function:

return_type operator operator_symbol(arg_list)


{
//body
}

- As a member function:
class class_name
{
//..................
public:
return_type operator operator_symbol(arg);
};

return_type class_name :: operator operator_symbol (arg)


{
//body
}

- For non-member friend function:

class class_name
{
//............
public:
friend return_type operator operator_symbol (arg, arg);
};

return_type operator operator_symbol(arg, arg)


{
//body
}

- The non-member operator function takes one more argument than the member operator function.
- For unary operator overloading, member function has no argument and non member function has one argument.
- For binary operator overloading, member function has one argument and non member function has two argument.

Rules of Operator Overloading

- After overloading, the meaning of operator can not be changed. So, use similar meaning only.
- The precedence, associativity and other syntactic characteristics of overloaded operator can not be changed.
- Use operator overloading only when necessary.
- Avoid ambiguity.
- New operators can not be created.
- Operator for basic types can not be created.

Unary Operator Overloading

- It is overloaded with non-static member function with no argument or non-member function taking one argument.
- As a non-static member function:

class class_name
{
//...........
public:
return_type operator operator_symbol(); //Prefix operator
return_type operator operator_symbol(int); //Postfix operator
//..................
};

return_type class_name :: operator operator_symbol() //Prefix operator overloading definition


{
//..........
}

return_type class_name :: operator operator_symbol(int) //Postfix operator overloading definition


{
//..........
}

- As a non-member function:

return_type operator operator_symbol(class_name) //Prefix operator overloading definition


{
//..........
}

return_type operator operator_symbol(class_name, int) //Postfix operator overloading definition


{
//..........
}

Overloading operator for prefix ++

#include

class counter
{
unsigned int count;
public:
counter() {count = 0;}
int ret_count()
{
return count;
}
void operator ++ ()
{
count++;
}
};

int main()
{
counter c1, c2;
cout << "c1 = " << c1.ret_count << "c2 = " << c2.ret_count;
++c1;
++c2;
++c2;
cout << "c1 = " << c1.ret_count << "c2 = " << c2.ret_count;
return 0;
}

Overloading operator for postfix ++

#include

class counter
{
unsigned int count;
public:
counter() {count = 0;}
counter(unsigned int n) : count(n) {}
int ret_count()
{
return count;
}
counter operator ++ (int);
};

counter counter :: operator ++ (int)


{
return counter(count++);
}

int main()
{
counter c1, c2;
cout << "c1 = " << c1.ret_count << "c2 = " << c2.ret_count;
c1++;
c2++;
c2++;
cout << "c1 = " << c1.ret_count << "c2 = " << c2.ret_count;
return 0;
}

Binary Operator Overloading

- By non static member function taking one argument or a non member function taking two arguments.

Overloading + operator
#include

class complex
{
float real, imag;
public:
complex()
{

}
complex(float rel, float img)
{
real = rel;
imag = img;
}
void display()
{
cout << real << " + i" << imag;
}
complex operator + (complex c);
};

complex complex :: operator + (complex c)


{
complex temp;
temp.real = real + c.real;
temp.imag = imag + c.imag;
return temp;
}

int main()
{
complex c1, c2, c3;
c1 = complex (4.4, 3.6);
c2 = complex (2.4, 3.5);
c3 = c1 + c2;
c3.display();
return 0;
}

Data Conversion

Conversion from Basic to User Defined Data Type


- It is done either by constructor or by overloading cast operator.

#include

class celcius
{
float temp;
public:
celcius() {}
celcius(float ftemp)
{
temp = (ftemp - 32) * 5 / 9;
}
void show()
{
cout << "Temp in celcius = " << temp;
}
};

int main()
{
celcius cel;
float fer;
cout << "Enter temp in fahrenheit : ";
cin >> fer;
cel = fer; // Basic to user defined
cel.showtemp();
return 0;
}

Conversion from User Defined to Basic


- It is done by overloading cast operator.

#include

class celcius
{
float temp;
public:
celcius() {
temp = 0;
}
void gettemp()
{
cout << "Temp in celcius = ";
cin >> temp;
}
operator float ()
{
float fer;
fer = (temp * 9 / 5) + 32;
return (fer);
}
};

int main()
{
celcius cel;
float fer;
cel.gettemp();
fer = cel;
cout << "Temp in Fahrenheit = " << fer;
return 0;
}

Conversion Between User Defined Type


- Conversion function can be defined in destination or source.
- To be defined in destination, one argument constructor is used.
- To be defined in source, cast operator function should be overloaded.

1. In Destination

// Program to convert polar coordinates to cartesian coordinates.


#include
#include

class polar
{
private:
float radius, angle;
public:
polar() {}
polar(float rad, float ang)
{
radius = rad;
angle = ang;
}
float return_rad()
{
return radius;
}
float return_ang()
{
return angle;
}
void display()
{
cout << "(" << radius << "," << angle << ")";
}
};

class cartesian
{
private:
float x, y;
public:
cartesian()
{
x = 0;
y = 0;
}
cartesian(float x0, float y0)
{
x = x0;
y = y0;
}
cartesian(polar p)
{
x = p.return_rad() * cos(p.return_ang());
y = p.return_rad() * sin(p.return_ang());
}
void display()
{
cout << "(" << x << "," << y << ")";
}
};

int main()
{
polar pol(10.0, 0.7853);
cartesian cart;
cart = pol;
cart.display();
return 0;
}

2. In Source

// Program to convert polar coordinates to cartesian coordinates.


#include
#include

class cartesian
{
private:
float x, y;
public:
cartesian()
{
x = 0;
y = 0;
}
cartesian(float x0, float y0)
{
x = x0;
y = y0;
}
void display()
{
cout << "(" << x << "," << y << ")";
}
};

class polar
{
private:
float radius, angle;
public:
polar() {
radius = 0;
angle = 0;
}
polar(float rad, float ang)
{
radius = rad;
angle = ang;
}
operator cartesian()
{
float x = static_cast (radius * cos(angle));
float y = static_cast (radius * sin(angle));
return cartesian(x, y);
}
void display()
{
cout << "(" << radius << "," << angle << ")";
}
};

int main()
{
polar pol(10.0, 0.7853);
cartesian cart;
cart = pol;
cart.display();
return 0;
}

Explicit Constructors

- The implicit conversion can be prevented by declaring explicit constructor.


- The keyword 'explicit' is used.
- It can be invoked explicitly.

class test
{
int data;
public:
test()
{
data = 0;
}
explicit test(int n)
{
data = n;
}
};

// Called as:
test t1(2);
6. Inheritance
Base and Derived Class
Inheritance
- Inheritance is the process of organizing information in a hierarchical form.
- It helps in code reusability.

- Inheritance is the mechanism of code reusability by deriving a new class which can inherits all or some of the
characteristics of base class and also can add new features.
- The class which is used to derive new classes is called base class.
- The new classes derived from the existing class are called derived class.
- Base class is also known as ancestor, parent or super class.
-Derived class is also known as descendant, child or sub class.

Protected Access Specifier

- It causes a member to be visible by the member function and friend function of a class where it is declared.
- The protected members are visible to derived class members and friend of classes derived from base class.
- The purpose of making data member protected in a class is to make such members accessible to derived class function.

Derived Class Declaration

- Derived class inherits all features of its parent class and add its own features too.
- Syntax

class derived_class_name : visibility_mode base_class_name


{
//members of derived class
};

Member Function Overriding

- The process of creating members in the derived class with the same name as that of the visible members of base class is
called overriding.
- It is called overriding as the new name overrides or hides the old name inherited from base class.

Illustration of Overriding

#include
class base
{
protected:
int num;
public:
void read()
{
cout << "Enter number in base : ";
cin >> num;
}
void show()
{
cout << "The number in base is : " << num;
}
};

class derived : public base


{
private:
int num;
public:
void read()
{
cout << "Enter number in derived : ";
cin >> num;
}
void show()
{
cout << "The number in derived is : " << num;
}
};

int main()
{
derived dl;
dl.read();
dl.show();
return 0;
}

Output:
-----------------
Enter number in derived : 5
The number in derived is : 5

Forms of Inheritance
Single Inheritance
- When a class is derived from only one base class, such derivation is called single inheritance.
Illustration:

#include

class student
{
private:
char name[30];
int id;
int age;
public:
void getdata()
{
cout << "Enter name, id and age : ";
cin >> name >> id >> age;
}
void show()
{
cout << name << id << age;
}
};

class leader : public student


{
private:
char union_name[25];
public:
void getdata()
{
student :: getdata();
cout << "Enter name of student union : ";
cin >> union_name;
}
void show()
{
student :: show();
cout >> union_name;
}
};

int main()
{
leader ld;
ld.getdata();
ld.show();
return 0;
}

Multiple Inheritance
- When a class is derived from two or more base class, it is called multiple inheritance.
Illustration:

#include

class school
{
private:
char school_name[30];
char address[40];
public:
void getdata()
{
cout << "Enter name of school and address : ";
cin >> school_name >> address;
}
void show()
{
cout << school_name << address;
}
};

class college
{
private:
char col_name[40];
long int phone;
public:
void getdata()
{
cout << "Enter name of college and phone number : ";
cin >> col_name, phone;
}
void show()
{
cout << col_name << phone;
}
};

class student : public school, public college


{
private:
char name[30];
int age;
public:
void getdata()
{
school :: getdata();
college :: getdata();
cout << "Enter name and age of student : ";
cin >> name >> age;
}
void show()
{
school :: show();
college :: show();
cout << name << age;
}
};

int main()
{
student s1;
s1.getdata();
s1.show();
return 0;
}

Multi Level Inheritance


- The derivation of a class from another derived class is called multi level inheritance.
Illustration:

#include
class company
{
private:
char company_name[30];
char address[40];
public:
void getdata()
{
cout << "Enter name of conpany and address : ";
cin >> company_name >> address;
}
void show()
{
cout << company_name << address;
}
};

class employee : public company


{
private:
char emp_name[40];
int id;
public:
void getdata()
{
company :: getdata();
cout << "Enter name of employee and id : ";
cin >> emp_name >> id;
}
void show()
{
company :: show();
cout << emp_name << id;
}
};

class manager : public employee


{
private:
float salary;
public:
void getdata()
{
employee :: getdata();
cout << "Enter salary of manager : ";
cin >> salary;
}
void show()
{
employee :: show();
cout << salary;
}
};

int main()
{
manager m1;
m1.getdata();
m1.show();
return 0;
}

Hierarchical Inheritance
- When two or more classes are derived from single base class, it is called hierarchical inheritance.
Illustration:

#include

class employee
{
private:
char emp_name[40];
int id;
public:
void getdata()
{
cout << "Enter name of employee and id : ";
cin >> emp_name >> id;
}
void show()
{
cout << emp_name << id;
}
};

class manager : public employee


{
private:
float salary;
public:
void getdata()
{
employee :: getdata();
cout << "Enter salary of manager : ";
cin >> salary;
}
void show()
{
employee :: show();
cout << salary;
}
};
class salesperson : public employee
{
private:
char degree[30];
public:
void getdata()
{
employee :: getdata();
cout << "Enter degree of salesperson : ";
cin >> degree;
}
void show()
{
employee :: show();
cout << degree;
}
};

int main()
{
manager m1;
m1.getdata();
m1.show();
salesperson s1;
s1.getdata();
s1.show();
return 0;
}

Hybrid Inheritance
- When more than one form of inheritance are mixed, it is called hybrid inheritance.

Multipath Inheritance and Virtual Base Class

- Creating a new derived class by multiple inheritance from base classes which are derived earlier from the same base class
is called multipath inheritance.
- In multipath inheritance shown in figure alongside, the classes B and C inherits the features of class A. The class D inherits
the same features from A through two paths B and C, causing ambiguity in accessing first base class A members.
- This ambiguity is eliminated by declaring base class as virtual while creating derived classes from the first base class.
Illustration of Multipath Inheritance

#include

class student
{
int roll;
char name[30];
public:
void getdata()
{
cout << "Enter name and roll number : ";
cin >> name >> roll;
}
void show()
{
cout << name << roll;
}
};

class test : virtual public student


{
protected:
float sem1, sem2;
public:
void getdata()
{
cout << "Marks of sem1 and sem2 : ";
cin >> sem1 >> sem2;
}
void show()
{
cout << sem1 << sem2;
}
};

class sport : virtual public student


{
protected:
float score;
public:
void getdata()
{
cout << "Score in sports : ";
cin >> score;
}
void show()
{
cout << score;
}
};

class result : public test, public sport


{
float total;
public:
void getdata()
{
stuent :: getdata();
test :: getdata();
sport :: getdata();
}
void show()
{
total = sem1 + sem2 + score;
student :: show();
test :: show();
sport :: show();
cout << total;
}
};

int main()
{
result r;
r.getdata();
r.show();
return 0;
}

Constructor Invocation

Constructor in Single and Multiple Inheritances


- In inheritance, when object of derived class is created, the base class constructor is called first and the constructor in
derived class is called next.
- If base class has no constructor or has a no argument constructor, it is not necessary to define constructor in derived class.
- If base class has parameterized constructor, the derived class must define a constructor and explicitly pass argument to base
class constructor. Otherwise, the base class constructor with argument is never invoked.

Constructor in Base Class Only

class base
{
public:
base()
{
cout << "From base class";
}
};

class derived : public base


{
// Body of derived class
};
int main()
{
derived d;
}

Output
---------------------------
From base class

Constructor in Derived Class Only

class base
{
//Body of base class
};

class derived : public base


{
public:
derived()
{
cout << "From derived class";
}
};

int main()
{
derived d;
}

Output
--------------------------
From derived class

Constructor in both base and derived class


- When there are default constructors in base as well as in derived class, the constructor of base is executed first and then
constructor of derived class is executed, when an object of derived class is created.

Constructor in Multiple Inheritance


- First constructor of base class on the order how base class is inherited.
- Then only the constructor of derived class.
For parameterized constructor

#include

class alpha
{
int x;
public:
alpha(int i)
{
x = i;
cout << "Alpha initialized";
}
void show()
{
cout << x;
}
};

class beta
{
int y
public:
beta(int j)
{
y = j;
cout << "Beta initialized";
}
void show_y()
{
cout << y;
}
};

class gamma : public alpha, public beta


{
int m, n;
public:
gamma(int a, int b, int c, int d) : alpha(a), beta(b)
{
m = c;
n = d;
cout << "Gamma initialized";
}
void show_mn()
{
cout << m << n;
}
};

int main()
{
gamma g(5, 10, 15, 20);
g.show();
g.show_y();
g.show_mn();
return 0;
}
Output
------------------------------
alpha initialized
beta initialized
gamma initialized
5
10
15 20

Destructors in Inheritance

- Calling of destructor is just in opposite sequence of that of the constructor.

7. Polymorphism and Dynamic Binding


Need of Virtual Function
Polymorphism
- Polymorphism is an ability of a single operation to react differently for various object call.
- Choosing function during compilation time is called static or early binding which includes function overloading and
operator overloading.
- Choosing function during execution time is called dynamic or late binding which can be done using virtual function.

Why virtual function is needed?


The program is efficient if the appropriate member function, when the base and derived class both have same function name
and prototype, could be selected while the program is running rather than at the compilation time. For this purpose, virtual
function is necessary. Such process is known as run time polymorphism. Virtual function requires the use of pointers.

Pointer to Derived Class

- C++ allows a pointer in a base class to point to either a base class object or to any derived class object.
- Example:
B *bptr; //Pointer to base class
B b; //Base object
D d; //Derived object
bptr = &b; //bptr pointer points to base class object
bptr = &d; //bptr pointer points to derived class object
- Here, bptr can only access those members of D that are inherited from B but can not access the original members of D.
- For this, C++ permits the pointer declared as pointer to derived class.

Illustration of Pointer to Inheritance

#include
class base
{
public:
int b;
void show()
{
cout << b;
}
};

class derived : public base


{
public:
int d;
void show()
{
cout << b;
cout << d;
}
};

int main()
{
base *bptr;
base b;
bptr = &b;
bptr -> b = 100;
bptr -> show();

derived d;
bptr = &d;
bptr -> b = 200;
bptr -> show();

derived *dptr;
dptr = &d;
dptr -> d = 300;
dptr -> show();

return 0;
}

Output
-----------------------
b = 100

b= 200

b= 200
d = 300
Definition of Virtual Function

- A virtual function is one which does not really exist but it appears real in some parts of a program.
- The exact member function is selected at run time.
- The keyword 'virtual' is used for defining virtual function.
- It must be defined in public.
- The syntax is:

class class_name
{
pivate:
// ...............
public:
virtual return_type function_name(args)
{
........
}
};

Array of Pointer to Base Class

- In case of hierarchical inheritance, the pointer to base class can access different functions belonging to different derived
classes using same object pointer with the help of array of pointers to base class using virtual function.

Illustration of Array of Pointers to Base Class

#include

class point
{
public:
virtual void draw()
{
cout << "point";
}
};

class line : public point


{
public:
void draw()
{
cout << "Line";
}
};
class circle : public point
{
public:
void draw()
{
cout << "Circle";
}
};

int main()
{
point pt;
line ln;
circle cr;

point *bptr[] = {&pt, &ln, &cr};

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


{
bptr[i] -> draw();
}
return 0;
}

Output
-----------------------
point
line
circle

Pure Virtual Function and Abstract Class

- A virtual function with null body is called pure virtual function.


- It only has function declaration.
- The base class which has at least one pure virtual function is called abstract class or abstract base class.
- Abstract class do not have any object.
- The syntax is:

class class_name
{
//...........
public:
virtual return_type function_name() = 0;
};

Illustration of Pure Virtual Function


#include

class rectangle
{
protected:
float l, b;
public:
rectangle()
{
l = 0;
b = 0;
}
virtual float perimeter()
{
return (2*(l+b));
}
virtual float area() = 0;
};

class square : public rectangle


{
public:
square()
{

}
square(float l, float b) : rectangle(l,b)
float area()
{
return l*b;
}
};

int main()
{
rectangle *bptr;
square sq(2,2);
bptr = &sq;
cout << "Perimeter = " << bptr -> perimeter();
cout << "Area = " << bptr -> area();
return 0;
}

Virtual Destructor

- Virtual constructor can not be created.


- Only virtual destructor can be created.
- Virtual destructor is a member function which is used to free the memory space effectively under late binding method.
- When base class destructor is made virtual, both base class and derived class destructor are called.
- Example:
class base
{
public:
base() {}
virtual ~base()
{
delete [] ptrbase;
cout << "Base class destructor";
}
};

class derived
{
//...........
};

void main()
{
base *bptr = new derived;
delete bptr;
}

reinterpret_cast Operator

- It is one of the cast operators that handles unrelated type conversion.


- The syntax is:
reinterpret_cast (expression);
- Example:

int ivar;
double dvar;
int *pivar;
double *pdvar;
void *pvoid;
pivar = reinterpret_cast (dvar)
pdvar = reinterpret_cast (ivar)

Run Time Type Information

- It is the ability of finding object's type and changing their type at run time.
- It is provided by the use of dynamic_cast and typeid.

dynamic_cast operator:
- It performs run time cast along with verifying validity of the cast.
- If cast is invalid, then the cast fails.
- Syntax : dynamic_cast (expression);
- It is used to cast from base class pointer to derived class pointer.
- Example:

animal *bptr, an;


cow *cptr, cw;
bptr = &cw;
cptr = dynamic_cast (bptr);

typeid operator:
- It returns reference to a standard library class type type_info defined in .
- The header file should be included.
- The syntax is:
typeid(expr);
Or,
typeid(type_name);

Missing chapters

 8. Stream Computation for Console and File I/O

 9. Templates

 10. Exception Handling

You might also like