Untitledet
Untitledet
Untitledet
DIPLOMA IN
INFORMATION COMMUNICATION
TECHNOLOGY
4
44
3
73
26
07
MODULE 2: SUBJECT NO 3
p
ap
ts
ha
W
Contents
CHAPTER 1: INTRODUCTION TO OBJECT ORIENTED PROGRAMMING ................ 4
Define Object Oriented Programming.................................................................................... 4
Evolution of Object Oriented Programming .......................................................................... 4
Programming paradigms ......................................................................................................... 4
Merits and demerits of OOP .................................................................................................... 5
Examples of object oriented languages ................................................................................... 5
Object Oriented Databases (OODBs) ..................................................................................... 5
CHAPTER 2: OBJECT ORIENTED PROGRAMMING CONCEPTS ................................. 7
Concepts associated with OOP ................................................................................................ 7
Objects and Classes............................................................................................................... 7
Abstraction and Encapsulation ......................................................................................... 10
Inheritance and polymorphism ......................................................................................... 11
4
Comparison between structured and OOP .......................................................................... 11
44
Keywords and identifiers ................................................................................................... 11
3
73
Comments and Punctuators ............................................................................................... 12
26
Reasons for embracing OOP.................................................................................................. 13
07
CHAPTER 3: LANGUAGE STRUCTURES OF OOP .......................................................... 14
p
ap
Basic Structure of C++ Program ........................................................................................... 14
ts
Features of the Object Oriented programming ................................................................... 17
ha
W
Header and Source Files and extensions ............................................................................... 17
Data Types in OOP ................................................................................................................. 21
Built-in/Simple Data Types .................................................................................................... 21
Derive Data Types ............................................................................................................... 23
User Defined Data Types .................................................................................................... 23
Variable and variable declaration ......................................................................................... 25
Declaration and Initialization ............................................................................................ 25
Scope of Variables ............................................................................................................... 26
Type Conversion and Type Casting ...................................................................................... 28
Implicit Type Conversions : ............................................................................................... 28
Explicit Type Conversion : ................................................................................................. 29
Type Compatibility ............................................................................................................. 30
CHAPTER4 : ESSENCE OF OBJECTS AND CLASSES ..................................................... 32
Objects and classes in OOP.................................................................................................... 32
Importance of objects and classes in OOP ........................................................................... 32
Implementation of objects and classes .................................................................................. 32
CHAPTER 5: INHERITANCE ................................................................................................. 44
Introduction and Rules in inheritance ............................................................................. 44
Types of inheritance ............................................................................................................. 45
Importance of Inheritance .................................................................................................. 45
Inheritance Advantages and Disadvantages ................................................................... 45
Implementation of Inheritance .......................................................................................... 46
Base & Derived Classes: ..................................................................................................... 46
Access Control and Inheritance: ....................................................................................... 47
Concepts in inheritance ...................................................................................................... 48
Inheritance and friends ...................................................................................................... 50
Pointers to objects ............................................................................................................... 52
Inheritance and constructors ............................................................................................. 54
Base class conversions......................................................................................................... 56
Overloading with Inheritance ............................................................................................ 60
Inheritance relationship ..................................................................................................... 60
CHAPTER 6: POLYMORPHISM ............................................................................................ 61
Introduction to Polymorphism ............................................................................................ 61
Advantages/importance of Polymorphism ............................................................................ 61
Encapsulation / Information hiding ...................................................................................... 64
Encapsulation / Information hiding subject properties ...................................................... 66
Virtual Function: ................................................................................................................ 66
Pure Virtual Functions: ...................................................................................................... 66
Data Abstraction ................................................................................................................. 67
4
Data Encapsulation ............................................................................................................. 69
44
Interfaces (Abstract Classes) ................................................................................................. 71
3
73
CHAPTER 7: CONSTRUCTORS AND DESTRUCTORS .................................................... 74
26
Definition of Constructors ...................................................................................................... 74
07
Types of Constructors............................................................................................................. 74
p
ap
Constructor Overloading ....................................................................................................... 76
ts
Destructors............................................................................................................................... 77
ha
W
Implementation of constructors and Destructors ................................................................ 78
CHAPTER 8: OPERATOR OVERLOADING ....................................................................... 79
Meaning and importance of operator overloading .............................................................. 79
Implementing Operator Overloading ................................................................................... 79
Overloading I/O operator....................................................................................................... 81
CHAPTER 9: FILE ORGANISATION.................................................................................... 87
Introduction to File organization ........................................................................................ 87
Description of File Stream...................................................................................................... 87
Files and Streams properties.................................................................................................. 87
CHAPTER 10: EMERGING TRENDS IN OOP ..................................................................... 92
CHAPTER 1: INTRODUCTION TO OBJECT
ORIENTED PROGRAMMING
Define Object Oriented Programming
A type of programming in which programmers define not only the data type of a data structure,
but also the types of operations (functions) that can be applied to the data structure. In this way,
the data structure becomes an object that includes both data and functions. In addition,
programmers can create relationships between one object and another. For example, objects can
inherit characteristics from other objects.
Object-oriented programming (OOP) is a programming paradigm based on the concept of
"objects", which are data structures that contain data, in the form of fields, often known as
attributes; and code, in the form of procedures, often known as methods. A distinguishing
feature of objects is that an object's procedures can access and often modify the data fields of the
object with which they are associated (objects have a notion of "this"). In object-oriented
programming, computer programs are designed by making them out of objects that interact with
one another. There is significant diversity in object-oriented programming, but most popular
4
44
languages are class-based, meaning that objects are instances of classes, which typically also
3
determines their type.
73
26
07
Evolution of Object Oriented Programming
p
ap
The object-oriented paradigm took its shape from the initial concept of a new programming
ts
ha
approach, while the interest in design and analysis methods came much later.
W
The first object–oriented language was Simula (Simulation of real systems) that was
developed in 1960 by researchers at the Norwegian Computing Center.
In 1970, Alan Kay and his research group at Xerox PARK created a personal computer
named Dynabook and the first pure object-oriented programming language (OOPL) -
Smalltalk, for programming the Dynabook.
In the 1980s, Grady Booch published a paper titled Object Oriented Design that mainly
presented a design for the programming language, Ada. In the ensuing editions, he
extended his ideas to a complete object–oriented design method.
In the 1990s, Coad incorporated behavioral ideas to object-oriented methods.
The other significant innovations were Object Modelling Techniques (OMT) by James
Rumbaugh and Object-Oriented Software Engineering (OOSE) by Ivar Jacobson.
Programming paradigms
A programming paradigm is a fundamental style of computer programming, a way of
building the structure and elements of computer programs.
The following are considered the main programming paradigms. There is inevitably some
overlap in these paradigms but the main features or identifiable differences are summarized
below:
Imperative programming – defines computation as statements that change a program state
Procedural programming, structured programming – specifies the steps the program must
take to reach the desired state.
Structured programming (sometimes known as modular programming) is a subset of
procedural programming that enforces a logical structure on the program being written to
make it more efficient and easier to understand and modify. Modular programming is the
process of subdividing a computer program into separate sub-programs.
Declarative programming – defines computation logic without defining its control flow.
Functional programming – treats computation as the evaluation of mathematical functions
and avoids state and mutable data
Object-oriented programming (OOP) – organizes programs as objects: data structures
consisting of datafields and methods together with their interactions.
Event-driven programming – the flow of the program is determined by events, such as
4
44
sensor outputs or user actions (mouse clicks, key presses) or messages from other programs
3
or threads.
73
Automata-based programming – a program, or part, is treated as a model of a finite state
26
machine or any other formal automata.
07
p
ap
ts
Merits and demerits of OOP
ha
W
Object-Oriented Programming has the following advantages over conventional approaches:
OOP provides a clear modular structure for programs which makes it good for defining
abstract datatypes where implementation details are hidden and the unit has a clearly defined
interface.
OOP makes it easy to maintain and modify existing code as new objects can be created with
small differences to existing ones.
OOP provides a good framework for code libraries where supplied software components can
be easily adapted and modified by the programmer. This is particularly useful for developing
graphical user interfaces.
Examples of object oriented languages
Many of the most widely used programming languages are multi-paradigm programming
languages that support object-oriented programming to a greater or lesser degree, typically in
combination with imperative, procedural programming. Significant object-oriented languages
include C++, Objective-C, Smalltalk, Delphi, Java, C#, Perl, Python, Ruby and PHP.
Terms:
A hybrid database - is usually an object-oriented framework created to act as an interface
between an "impure" object-oriented language like C++ and a relational database manager. The
hybrid manager allows the language to access the database as though it were truly
object-oriented, while leaving the database itself unchanged. The hybrid design allows the
object-oriented programmer to use nearly any OOP feature that they want (much like an
OODBMS), while keeping the database itself relational which allows the use of commercially
available and supported products, allowing the "best of both worlds" at the cost of the run-time
overhead to support the hybrid framework.
Persistent object oriented databases - data manipulated by the application is transient and data
in the database is persisted (Stored on a permanent storage device). In object databases, the
application can manipulate both transient and persisted data. Persistence is often defined as
4
44
objects (and their classes in the case of OODBs) that outlive the programs that create them.
3
73
Pure object oriented databases is based solely on the object-oriented data model
26
07
p
ap
ts
ha
W
CHAPTER 2: OBJECT ORIENTED
PROGRAMMING CONCEPTS
Concepts associated with OOP
Concepts of OOP:
Objects Polymorphism
Classes Overloading
Data Abstraction and Encapsulation Reusability
Inheritance
4
Class is a collection of data member and member function. Class is a user define data
44
type. Object is a class type variable. Objects are also called instance of the class. Each
3
73
object contains all members (variables and functions) declared in the class.
26
07
A class is the collection of related data and function under a single name. A C++
p
program can have any number of classes. When related data and functions are kept
ap
ts
under a class, it helps to visualize the complex problem efficiently and effectively.
ha
W
4
44
class temp
3
73
{
26
private:
07
int data1;
p
float data2;
ap
public:
ts
ha
void func1()
W
{ data1=2; }
float func2(){
data2=3.5;
retrun data;
}
};
Explanation
As mentioned, definition of class starts with keyword class followed by name of
class(temp) in this case. The body of that class is inside the curly brackets and
terminated by semicolon at the end. There are two keywords: private and public
mentioned inside the body of class.
Objects
When class is defined, only specification for the object is defined. Object has same
relationship to class as variable has with the data type. Objects can be defined in
similary way as structure is defined.
4
func1() and func2() are member functions.
44
3
73
Accessing Data Members and Member functions
26
Data members and member functions can be accessed in similar way the member of
07
structure is accessed using member operator(.). For the class and object defined above,
p
ap
func1() for object obj2 can be called using code:
ts
obj2.func1();
ha
W
Similary, the data member can be accessed as:
object_name.data_memeber;
Note: You cannot access the data member of the above class temp because both data
members are private so it cannot be accessed outside that class.
Explanation of Program
4
44
In this program, two data members data1 and data2 and two member function
3
int_data() and float_data() are defined under temp class. Two objects obj1 and obj2 of
73
that class are declared. Function int_data() for the obj1 is executed using code
26
obj1.int_data(12);, which sets 12 to the data1 of object obj1. Then, function
07
float_data() for the object obj2 is executed which takes data from user; stores it in data2
p
ap
of obj2 and returns it to the calling function.
ts
ha
Note: In this program, data2 for object obj1 and data1 for object obj2 is not used and
W
contains garbage value.
4
44
int money;
3
73
Here, int is a keyword that indicates, 'money' is of type integer.
26
07
As, C++ programming is case sensitive, all keywords must be written in lowercase.
p
Here is the list of all keywords predefined by C++.
ap
ts
ha
Keywords in C++ Language
W
auto double int struct
do if static while
Identifiers
In C++ programming, identifiers are names given to C++ entities, such as variables,
functions, structures etc. Identifier are created to give unique name to C++ entities to
identify it during the execution of program. For example:
int money;
int mango_tree;
Here, money is a identifier which denotes a variable of type integer. Similarly,
mango_tree is another identifier, which denotes another variable of type integer.
4
44
in a program should be different.
3
73
26
Literals and constants
07
p
A literal is some data that's presented directly in the code, rather than indirectly
ap
through a variable or function call.
ts
ha
W
Here are some examples, one per line:
42
128
3.1415
'a'
"hello world"
A value written exactly as it's meant to be interpreted. In contrast, a variable is a name
that can represent different values during the execution of the program. And a constant
is a name that represents the same value throughout a program. But a literal is not a
name -- it is the value itself
4
based on the operands(literals).
44
3
73
Reasons for embracing OOP
26
Code Reuse and Recycling: Objects created for Object Oriented Programs can easily
07
be reused in other programs.
p
ap
Encapsulation (part 1): Once an Object is created, knowledge of its implementation
ts
is not necessary for its use.
ha
W
CHAPTER 3: LANGUAGE STRUCTURES OF
OOP
Basic Structure of C++ Program
As C++ is a programming language so it follows a predefined structure. The program
is divided into many sections, it is important to know the need of every section. The
easiest way to understand the basic structure of c++ program is by writing a program.
The basic C++ program is as follows:
//simple c++ program
int main()
4
44
{
3
73
int a=10,b=34;
26
07
cout<<"simple c++ program \n"; // c++ statement
p
ap
ts
ha
cout<<"hello world";
W
cout<<a<<b;
The basic structure of c++ program mentioned above can be divided into following
sections:
Documentation Section : This section comprises of comments. As the name
suggests, this section is used to improve the readability and understanding of the
program.// (Double Slash) represents comments in C++ program. Comments can
be of single line or multiple lines. Double Slash comments are used to represent
single line comments. For multiple line comment, you can begin with /* and end
with */. For example :
/* Text line number 1
Text line number 2
Text line number 3 */
In the above C++ program //simple c++ program represents single line comment.
Linking and Directives Section : The program written above begins with
#include<iostream>. <iostream> represents header file which includes the
functionalities of predefined functions. In linking section, the compiler in-built
functions such as cout<<, cin>> etc are linked with INCLUDE subdirectory‘s header
file <iostream>. The ‗#‘ symbols tells about ―address to‖ or ―link to‖. Iostream is
input/output stream which includes declarations of standard input-output library in c++.
main() Section : This is the section in which the program coding is written.
Basically, it acts as a container for c++ program. The execution of the c++ program
begins with main() function and it is independent of the location of main() function in
the program. main() is a function as represented by parenthesis ―()‖. This is because it
is a function declaration. The body of the main() function can be found right after these
parenthesis, the body is enclosed in braces ―{ }‖.
Body of main() Section : The body of the main() function begins with ―{―.
o Local Variable Declaration : In this the variables which are used in the body o
f the main() functions are declared. These are called the local variables as their
4
scope is limited within the main() function only, unless they are declared
44
globally outside the main() function. ‖ int a=10, b=34;‖ in the above program
3
73
represents local variables
26
07
o Statements to Execute : This section includes statements for reading, writing
p
ap
and executing data using I/O functions, library functions, formulas, conditional
ts
statements etc. Above written program has many executable statements
ha
like cout<<“simple c++ program \n”;
W
o return 0; in the above program causes the function to finish and 0 represents
that function has been executed with zero errors. This is considered as most
usual way to end a C++ program.
2 which
3 explains
4 the structure of c++ program */
7 float f=10.2,j=4.5;
8 int main()
9 {
10 int a=10,b=34;
12 cout<<"hello world";
4
44
cout<<a<<b;
3
13
73
26
return 0; // returning no errors
07
14
p
}
ap
15
ts
ha
W
Multiple line comments :
/* basic example
which
explains
the structure of c++ program */ .
float f=10.2, j=4.5; are global variables which are declared outside the main()
function.
The statements written in the above mentioned programs can be written in a single line
for example :
int main(){int a=10,b=34; cout<<"simple c++ program \n";
cout<<"hello world"; cout<<a<<b; return 0;}
4
44
3
Header and Source Files and extensions
73
In this lesson we will talk about some relatively new concepts that I‘ve postponed over
26
07
and over, until this point, where we can actually use them for a better understanding.
p
We will talk about separating your code into separate header and source files.
ap
ts
ha
You will finally see what headers look like and how we can use them to separate
W
different parts of our code into separate source files and header files. In this way we
can keep our code more organized, by separating different concepts, which will make it
much easier to find what we are looking for when trying to modify our program.
There are also much more upsides of doing this, and we will go through each one of
them, but let‘s first take a look at what headers really are and look like.
Header files
You‘ve been using the help of a header file even from the first program that we wrote
in our lessons. If you remember, I‘ve explained, in a very general way, what headers
are, when we‘ve first encountered the #include <iostream> in our programs.
Headers usually have the .h extension and contain declarations that we will use in our
source files. Let‘s take as an example the iostream header file that we include when
working with input-output in our program. We could have never used cout to print to
the screen without including the iostream header file because we have never declared
and defined that identifier anywhere in our program. That is why we are telling the
compiler to include the iostream header file, which actually means that, the compiler
will locate and read all the declarations from that header file when it reaches the
preprocessor directive, #include.
Usually header files only contain declarations and do not provide the actual definitions.
When we only declare a function and do not provide the definition for it, when we are
calling that function in our program, the linker will complain about ―Unresolved
Symbols―. So, how does the compiler know where to get the definition for cout then?
Well, the cout is actually defined in the standard runtime library which is
automatically linked in the link process.
4
44
When using libraries, you do not have to compile the code again, which would be a
3
73
waste of time, because libraries are always provided as they are, without the need of
26
modifying them. When using a library that is not from the standard runtime, you will
07
also need to let the compiler know which libraries you wish to include, so it knows
p
ap
where to get the symbols from and link them, once they are used in your program.
ts
ha
For now, we will not use separate libraries, but we will get to learn how all of these
W
new concepts work by using separate source files and header files in our project.
mathPrimer.h
// mathPrimer.h
// ChapterII.HeaderSourceFiles
//
// Created by Vlad Isan on 20/04/2013.
// Copyright (c) 2013 INNERBYTE SOLUTIONS LTD. All rights
reserved.
//
#ifndef mathPrimer_h
#define mathPrimer_h
#endif
First, let‘s take a look a little at the preprocessor directives in this file. You already
know what #define is, as we have covered it a little when talking about variables and
constants. Let‘s talk a little about the conditional compilation, #ifdef, #ifndef
and #endif.
The conditional compilation preprocessor directives, tell your compiler what should
be compiled or not and under what conditions.
The #ifdef preprocessor directive basically checks if something was previously defined
using the #define preprocessor directive. If this condition is met, then the code between
the #ifdef and the corresponding #endif is compiled, otherwise it is ignored by the
compiler.
The same goes for #ifndef, and, as you can already imagine, it is the complete opposite
of #ifdef, and it allows the compiler to check whether a name has not been defined
4
with #define.
44
So, why are we using these preprocessor directives in our header file? These
3
73
preprocessor directives in the header files are called header guards, and helps us to
26
avoid including the same declaration in multiple times.
07
This works by skipping the entire contents of the header file if it was already included
p
ap
in some other place. In our example, when you first include our header
ts
file, mathPrimer.h, the #ifndef condition is met, because we haven‘t defined the
ha
W
name mathPrime_h by using the #define preprocessor directive until now. So, the
condition is met and everything inside the header file will be compiled, and most
importantly, the mathPrimer_h will be defined as well, by using the #define
mathPrimer_h right after the #ifndef. Now, when you include the header file a
second time, the #ifndef mathPrimer_h condition will not be met, because we have
already defined that name when we included the header file in some other place.
By using these header guards we are avoiding the complaint we could get from the
compiler when declaring the header contents twice, or even multiple times.
OK, now let‘s look at what is declared inside our mathPrimer.h header file. We have
two function declarations, add and subtract, both having two integer parameters and
an integer return type.
We have to also define our functions. Let‘s create another file called mathPrimer.cpp.
This file will contain the function definitions:
mathPrimer.cpp
//
// mathPrimer.cpp
// ChapterII.HeaderSourceFiles
//
// Created by Vlad Isan on 20/04/2013.
// Copyright (c) 2013 INNERBYTE SOLUTIONS LTD. All rights
reserved.
#include "mathPrimer.h"
4
44
in.
3
73
Please note that when we only have declarations in the header files, we do not need to
26
include the header file when defining the functions, as we do in our case. We have to
07
only include it when we are calling the functions declared in it. But, as we already are
p
ap
using header guards, it is a good practice to include it in here as well, because header
ts
files can also contain constants which could be used in here as well. As an example,
ha
W
we can declare a constant in our header file to hold the value of PI, and use that
constant when defining the other functions, in our mathPrimer.cpp.
As you can notice, we are also defining the functions add and subtract which we are
going to use in our main function.
Now, let‘s take a look at our main.cpp:
// main.cpp
// ChapterII.HeaderSourceFiles
//
// Created by Vlad Isan on 20/04/2013.
// Copyright (c) 2013 INNERBYTE SOLUTIONS LTD. All rights
reserved.
//
#include <iostream>
#include "mathPrimer.h" /* including our header file */
int main()
{
return 0;
}
As you can see we are including our header file in here as well, so we can use
the functions declared in it, add and subtract. If you were to remove the #include
“mathPrimer.h” from here, you will see that you cannot compile the code, because the
compiler would not know anything about those functions, and it will complain about
―Undeclared identifiers―.
An important thing to note about header files is to never include variables in them,
unless they are constants. Header files should only be used for declarations. Also, you
should never include the definition for a function in the header file because it will
change the whole scope of having a header file, and it will make it hard to read.
4
44
Also, you should always split the parts of your code into separate header and source
3
73
files grouped by a certain criteria or functionality, because when only needing a part of
26
it, you do not need to include all of the declarations that reside in your program. As in
07
our example, we have called our header file mathPrime.h, as it will only contain basic
p
math functions. If we want to make some other helper functions, for example, for
ap
ts
printing to the screen and retrieving user input, we should make another pair
ha
of header/source files, that we should only include when needed.
4
quantities. Examples of valid floating point numbers are: 35.5, -66.3, and 49.07.
44
A float type data can be used to hold numbers from 3.4*10-38 to 3.4*10+38 with
3
73
six or seven digits of precision. However, for more precision a double precision
26
type (double) can be used to hold numbers from 1.7*10-308 to 1.7*10+308 with
07
about 15 digits of precision.
p
ap
ts
Void data type:
ha
It is used for following purposes;
W
o It specifies the return type of a function when the function is not returning any
value.
o It indicates an empty parameter list on a function when no arguments are
passed.
o A void pointer can be assigned a pointer value of any basic data type.
4
Function
44
Pointer and
3
73
Reference
26
Array An array is a set of elements of the same data type that are referred to by the
07
same name. All the elements in an array are stored at contiguous (one after another)
p
ap
memory locations and each element is accessed by a unique index or subscript value.
ts
ha
The subscript value indicates the position of an element in an array.
W
Function A function is a self-contained program segment that carries out a specific
well-defined task. In C++, every program contains one or more functions which can be
invoked from other parts of a program, if required.
Reference A reference is an alternative name for a variable. That is, a reference is an
alias for a variable in a program. A variable and its reference can be used
interchangeably in a program as both refer to the same memory location. Hence,
changes made to any of them (say, a variable) are reflected in the other (on a reference).
Pointer A pointer is a variable that can store the memory address of another variable.
Pointers allow to use the memory dynamically. That is, with the help of pointers,
memory can be allocated or de-allocated to the variables at run-time, thus, making a
program more efficient
4
,city[20]
44
,state[3]
3
73
,zip_code[11]
;
26
int age;
07
float height
p
ap
,weight
ts
;
ha
double salary;
W
};
Where tag is optional and only needs to be present if no variable is present. The
members are variables declared as any C supported data type or composed data type. A
structure is a set of values that can be referenced collectively through a variable name.
The components of a structure are referred to as members of a structure. A structure
differs from an array in that members can be of different data types. A structure is
defined by creating a template. A structure template does not occupy any memory
space and does not have an address, it is simply a description of a new data type. The
name of the structure is the tag. The tag is optional when a variable is present and the
variable is optional when the tag is present. Each member-declaration has the form
A Class specified by the keyword class, is a user defined type that contains both data
members and member functions...
A union is a user-defined data or class type that, at any given time, contains only one
object from its list of members (although that object can be an array or a class type).
4
44
3
73
26
07
p
ap
ts
ha
W
Program Example
Let's look at an example of how to declare an integer variable in the C++ language
and use it.
4
44
int main()
3
{
73
int age;
26
07
age = 10;
p
cout<<"The data in variable age is %d yrs.\n"<< age;
ap
ts
return 0;
ha
W
}
This C program would print ―The data in variable age is 10 yrs."
int main()
{
String name;
int age;
cout<<"Enter your name plz:\n";
cin>>name;
cout<<"Enter your age plz:\n";
cin>>age;
return 0;
}
This C program would print "Your Name is KIM and your age is 10 yrs".
Scope of Variables
All the variables have their area of functioning, and out of that boundary they don't hold
their value, this boundary is called scope of the variable. For most of the cases its
between the curly braces,in which variable is declared that a variable exists, not outside
it. We will study the storage classes later, but as of now, we can broadly divide
variables into two main types,
Global Variables
Local variables
Global variables
Global variables are those, which ar once declared and can be used throughout the
lifetime of the program by any class or any function. They must be declared outside the
main() function. If only declared, they can be assigned different values at different
time in program lifetime. But even if they are declared and initialized at the same time
outside the main() function, then also they can be assigned any value at any point in the
program.
Example : Only declared, not initialized
include <iostream>
4
44
using namespace std;
int x; // Global variable declared
3
73
int main()
26
{
07
x=10; // Initialized once
cout <<"first value of x = "<< x;
p
ap
x=20; // Initialized again
ts
cout <<"Initialized again with value = "<< x;
ha
}
W
Local Variables
Local variables are the variables which exist only between the curly braces, in which its
declared. Outside that they are unavailable and leads to compile time error.
Example :
include <iostream>
using namespace std;
int main()
{
int i=10;
if(i<20) // if condition scope starts
{
int n=100; // Local variable declared and initialized
} // if condition scope ends
cout << n; // Compile time error, n not available here
}
4
44
3
73
Both Type conversion and Type casting in C++ are used to convert one predefined type
26
to another type.
07
Type Conversion is the process of converting one predefined type into another type.
p
ap
and type Casting is the converting one predefined type into another type forcefully.
ts
ha
Need of Type Conversion and Type Casting in C++
W
An Expression is composed of one or more operations and operands. Operands consists
of constants and variables. Constants and expressions of different types are mixed
together in an expression. so they are converted to same type or says that a conversion
is necessary to convert different types into same type.
4
44
After applying above arithmetic conversions, each pair f operands is of same type and
3
the result of each operation is the same as the type of both operands.
73
26
Example of Implicit Type Conversion :
07
p
ap
ts
ha
W
4
44
3
73
26
07
Type Compatibility
p
ap
In an assignment statement, the types of right types and left side of an assignment
ts
should be compatible, so that conversion can take place. For example,
ha
W
ch=x; (where ch is of char data type and x is of integer data type)
How and Why Information is loose ?
what is Big Endian ?? ⇒ refer to the link Click here
since the memory representation in Big-Endian, Let
int x=1417;
ch=x;
now, x will be 00000101 10001001 in binary.
So, the information i.e. the value stores at address 1001, will be lost after assigning an
integer variable value to a character variable
4
44
3
73
26
07
p
ap
ts
ha
W
CHAPTER4 : ESSENCE OF OBJECTS AND
CLASSES
Objects and classes in OOP
A class is a template definition of the method s and variable s in a particular kind of
object. Thus, an object is a specific instance of a class; it contains real values instead of
variables.
4
44
anything about. They simply have to know what services the object offers and how to
3
access them.
73
26
07
Another important dimension of OOP is ―loose coupling.‖ Well-written classes make it
p
ap
so that it is possible to easily replace portions of programming code without impacting
ts
the rest of the system. In a well-written OOP architecture, you can switch databases
ha
without having to touch the code in your control or view layers.
For value types, like int the compiler will give them a valid value if you do not do so
explicitly. int's initialize to zero by default, DateTime's initialize to
DateTime.MinValue by default.
Reference type variables initialize to the object you give it. The compiler will not
assign an object (i.e. a valid value) if you don't. In this case the value is null -
nothing. So we say that the reference is initialized to null.
Objects are Instantiated
Humans are born. Objects are instantiated. A baby is an instance of a Human, an object
is an instance of some Class.
The act of creating an instance of a Class is called instantiation
Free store
Static Storage vs Heap vs Stack
1. Static vs Dynamic
Static: Storage can be made by compiler looking only at the text of the program. One
reason for statically allocating as many data objects as possible is that the addresses of
these objects can be compiled into target code.
Dynamic: Storage can be made by looking at what the program does when the program
is running.
2. Static
4
44
Global constants and other data generated by the compiler (e.g. info to support garbage
3
73
collection) are allocated static storage. Static variables are bound to memory cells
26
before execution begins and remains bound to the same memory cell throughout
07
execution. E.g., C static variables.
p
ap
Advantage: efficiency (direct addressing), history-sensitive subprogram support
ts
ha
Disadvantage: lack of flexibility, no recursion if this is the *only* kind of variable, as
W
was the case in FORTRAN
3. Heap/free-store
Data that may outlive the call to the procedure that created it is usually allocated on a
heap. E.g. new to create objects that may be passed from procedure to procedure.
The size of heap cannot be determined at compile time. Referenced only through
pointers or references, e.g., dynamic objects in C++, all objects in Java
Advantage: provides for dynamic storage management
Disadvantage: inefficient and unreliable
4. Stack
Names local to a procedure are allocated space on a stack. The size of stack can not be
determined at compile time.
Advantages: allows recursion conserves storage
Disadvantages: Overhead of allocation and deallocation Subprograms cannot be history
sensitive
Inefficient references (indirect addressing)
Static objects
Static Objects: Global objects, static data members, file scope objects and local
variables declared static are variables with static storage duration. A strategy for
initialization of objects with static storage duration is needed to avoid the risk of
accessing uninitialized objects.
Objects with static storage duration should only be declared within the scope of a
class, function or anonymous namespace.
Static objects make it possible to access an object inside a function without having to
pass along a pointer or reference to it. Many objects can use the same object without
each object storing a pointer to the object, which can save space and sometimes make
the code less complex.
4
44
}
3
73
26
Implicit pointer
07
p
In object-oriented programming, type conversion allows programs to treat objects of
ap
one type as one of their ancestor types to simplify interacting with them.
ts
ha
W
In most languages, the word coercion is used to denote an implicit conversion, either
during compilation or during run time. A typical example would be an expression
mixing integer and floating point numbers (like 5 + 0.1), where the integers are
normally converted into the latter. Explicit type conversions can either be performed
via built-in routines (or a special syntax) or via separately defined conversion routines
such as an overloaded object constructor.
A pointer is a programming language object, whose value refers directly to (or "points
to") another value stored elsewhere in the computer memory using its address. implicit
conversion help result of data pointed to by a pointer be converted to respective type of
type of the pointer
Example, in C++
int *money;
char *bags;
money would be an integer pointer and bags would be a char pointer. The following
would yield a compiler warning of "assignment from incompatible pointer type"
bags = money;
Because money and bags were declared with different types. To suppress the compiler
warning, it must be made implicit that you do indeed wish to make the assignment by
typecasting it
bags = (*char) money; //implicit conversion
bags = (char*) money; // implicit conversion
In-line function
Inline Functions
An inline function is a function whose statements are embedded in the caller as a
substitute for the function call. This avoids the overhead a context switch which must
be performed whenever a function is called and whenever a function returns to the
caller. The only purpose for inlining is to increase the execution speed of a program.
Inline functions should be small and simple. Since a function may be called from many
4
different places in a program, inlining large functions can result in an undesirable
44
increase in the size of a program. Inline functions should not contain any function calls
3
73
or I/O statements. As a general rule, if a function has more than five statements it
26
should not be inlined.
07
p
When you specify that a function is an inline function, it is merely a request of the
ap
ts
compiler. The compiler may or may not actually inline the function.
ha
W
Inlining Global Functions
To inline a global function:
Put the keyword inline before the return type in the function header.
Make sure that the function definition (not just the prototype) appears before
any calls to the function.
Example:
inline void swap(int &a, int &b)
{
int c = a;
a = b;
b = c;
}
int main()
{
int x = 5;
int y = 10;
swap(x,y);
cout << x << " " y << endl;
}
Inlining Member Functions
There are two ways to inline a member function: implicit and explicit.
Implicit
In implicit inlining, the inline member function is defined within the class definition.
The keyword inline is not used.
Example:
class Date
{
public:
Date(int mm,int dd,int yy) {month = mm; day = dd; year
= yy;}
void setdate(int mm,int dd,int yy)
{month = mm; day = dd; year = yy;}
void showdate(); // not inlined
4
44
private:
3
int month;
73
int day;
26
int year;
07
};
p
ap
Explicit
ts
ha
In explicit inlining, the prototype in the class definition is preceded by the keyword
W
inline. The member function defintion is defined outside the class definition, and is also
preceded by the keyword inline.
Example:
class Date
{
public:
inline Date(int,int,int);
inline void setdate(int,int,int);
void showdate(); // not inlined
private:
int month;
int day;
int year;
};
void showdate()
{
cout << month << '/' << day << '/' << year;
}
Friend of class
4
44
A friend class in C++ can access the "private" and "protected" members of the class in
3
73
which it is declared as a friend
26
Example
07
class B {
p
friend class A; // A is a friend of B
ap
ts
ha
private:
W
int i;
};
class A {
public:
A(B b) {
b.i = 0; // legal access due to friendship
}
};
Features
Friendships are not symmetric – If class A is a friend of class B, class B is not
automatically a friend of class A.
Friendships are not inherited – A friend of class Base is not automatically a friend
of class Derived and vice versa; equally if Base is a friend of another class,
Derived is not automatically a friend and vice versa.
4
44
class c {
3
73
int i;
26
07
int j;
p
ap
static int m;
ts
ha
W
static int n;
public:
void zap();
static void clear();
};
void c::zap() {
i = 0; j = 0; m = 0; n = 0;
}
void c::clear() {
m = 0; n = 0;
}
i and j are instance variables and m and n are class variables. Every object of class c
will have its own private i and j, which can have different values for different objects;
however, all objects will access the same m and n, which will, of course, have the same
values for all objects.
Static variables are like non-inline member functions in that they are declared in a class
declaration and defined in the corresponding source file. To define static variables m
and n, the source file for class c must contain the following declarations (which are
also definitions):
int c::m;
int c::n;
These definitions can also be used to assign initial values to the static member
variables. For example, the following definitions give m the initial value 5 and n the
initial value 6:
int c::m = 5;
4
44
3
int c::n = 6;
73
26
07
The accessibility rules for class variables are the same as for instance variables.
p
ap
Thus private and protected class variables can be accessed by member and friend
ts
functions, but not by functions that are not associated with the class. Likewise, a
ha
derived class with a public base class inherits access to the protected and public class
W
variables of the base class.
In addition, we can define static member functions that can manipulate only static
member variables – they cannot access the instance variables of class objects. Like
static member variables, static member functions are associated with a class rather than
with any class object. A static member function is invoked via the name of the class
rather than via the name of a class object.
The preceding example defines an ordinary member function zap() and a static
member function clear(). To invoke the ordinary member function zap(), we
must declare a class object cc and apply zap() to it with the dot operator:
c cc; // declare cc as c object
cc.zap(); // apply zap() to class object cc
From the definition of zap(), we note that it can manipulate the instance variables i and
j of cc as well as the class variables m and n.
In contrast, the static member function clear() is invoked using the name of the class
and the :: operator:
c::clear();
We can call clear() even if no class objects have been created. From the definition of
clear(), we note that it manipulates only the class variables m and n; clear() does not
have access to the instance variables i and j of any class object.
An enumerated type (also called enum ) is a data type consisting of a set of named
4
values called elements, members or enumerators of the type.
44
3
73
Syntax: enum type_name{ value1, value2,...,valueN };
26
07
p
Example:
ap
1) enum Color {Red, Green, Blue};
ts
ha
W
2) enum week{ sunday, monday, tuesday, wednesday, thursday,
friday, saturday};
typedef keyword allows the programmer to create new names for types such as int or it
literally stands for "type definition". Typedefs can be used both to provide more clarity
to your code and to make it easier to make changes to the underlying data types that
you use.
Note:
Typedef is a keyword that is used to give a new symbolic name for the existing
name in a C program. This is same like defining alias for the commands.
Consider the below structure.
struct student
{
int mark [2];
char name [10];
float average;
}
1st way :
struct student record; /* for normal variable */
struct student *record; /* for pointer variable */
2nd way :
typedef struct student status;
When we use “typedef” keyword before struct <tag_name> like above, after that
we can simply use type definition “status” in the C program to declare structure
variable.
This is equal to “struct student record”. Type definition for “struct student” is
status. i.e. status = “struct student”
An alternative way for structure declaration using typedef in C:
typedef struct student
4
44
{
3
73
int mark [2];
26
char name [10];
07
float average;
p
} status;
ap
ts
ha
To declare structure variable, we can use the below statements.
W
status record1; /* record 1 is structure variable */
status record2; /* record 2 is structure variable */
Enumerated constant
An enumeration is a distinct type whose value is restricted to one of several explicitly
named constants ("enumerators"). The values of the constants are values of an
integral type known as the underlying type of the enumeration.
Pointer to members
Pointer-to-Member Operators: .* and ->*
Syntax
expression .* expression
expression –>* expression
Simple Example
We can define pointer of class type which can be used to point to class objects
4
44
3
73
26
07
p
ap
ts
ha
W
Here you see that we have declared a ppointer of class type which points to class‘s
object. We can access data members and member fucntions using pointer name with
arrow ->symbol.
nested classes
Nested class is a class defined inside a class, that can be used within the scope of the class in
which it is defined.
Example:
class Nest
{
public:
class Display
{
private:
int s;
public:
void sum( int a, int b)
{ s =a+b; }
void show( )
{ cout << "\nSum of a and b is:: " << s;}
};
};
void main()
{
Nest::Display x;
x.sum(12, 10);
x.show();
}
Result:
Sum of a and b is::22
4
44
supported as elements.
3
73
26
The container manages the storage space for its elements and provides member
07
functions to access them, either directly or through iterators (reference objects with
p
similar properties to pointers).
ap
ts
ha
Containers replicate structures very commonly used in programming: dynamic arrays
W
(vector), queues (queue), stacks (stack), heaps (priority_queue), linked lists (list), trees
(set), associative arrays (map)...
CHAPTER 5: INHERITANCE
Introduction and Rules in inheritance
In OOP, we often organize classes in hierarchy to avoid duplication and reduce
redundancy. The classes in the lower hierarchy inherit all the variables (static
attributes) and methods (dynamic behaviors) from the higher hierarchies. A class in the
lower hierarchy is called a subclass (or derived, child, extended class). A class in the
upper hierarchy is called a superclass (or base, parent class). By pulling out all the
common variables and methods into the superclasses, and leave the specialized
variables and methods in the subclasses, redundancy can be greatly reduced or
eliminated as these common variables and methods do not need to be repeated in all the
subclasses. For example,
4
44
3
73
26
07
p
ap
ts
ha
Example W
The following C++ code establishes an explicit inheritance relationship between classes
B and A, where B is both a subclass and a subtype of A, and can be used as an A
wherever a B is specified (via a reference, a pointer or the object itself).
class A
{ public:
void DoSomethingALike() const {}
};
class B : public A
{ public:
void DoSomethingBLike() const {}
};
void SomeFunc()
{
B b;
UseAnA(b); // b can be substituted for an A.
}
Types of inheritance
There are various types of inheritance, depending on paradigm and specific language.
Single Inheritance : In the single inheritance, subclasses inherits the features of
a single super class. A class acquire the property of another class.
Multiple Inheritance : Multiple Inheritance allows a class to have more than
one super class and to inherit features from all parent class.
Multilevel Inheritance : In multilevel inheritance a subclass is inherited from
another subclass.
Hierarchical Inheritance : In hierarchical inheritance a single class serves as a
superclass (base class) for more than one sub class.
4
44
Hybrid Inheritance : It is a mixture of all the above types of inheritance.
3
73
26
Importance of Inheritance
07
p
ap
Inheritance is a good choice when:-
ts
ha
W
Your inheritance hierarchy represents an "is-a" relationship and not a "has-a"
relationship.
You can reuse code from the base classes.
You need to apply the same class and methods to different data types.
The class hierarchy is reasonably shallow, and other developers are not likely to
add many more levels.
You want to make global changes to derived classes by changing a base class.
1. One of the key benefits of inheritance is to minimize the amount of duplicate code in
an application by sharing common code amongst several subclasses. Where
equivalent code exists in two related classes, the hierarchy can usually be refactored
to move the common code up to a mutual superclass. This also tends to result in a
better organization of code and smaller, simpler compilation units.
2. Inheritance can also make application code more flexible to change because classes
that inherit from a common superclass can be used interchangeably. If the return type
of a method is superclass
3. Reusability -- facility to use public methods of base class without rewriting the same
4. Extensibility -- extending the base class logic as per business logic of the derived class
5. Data hiding -- base class can decide to keep some data private so that it cannot be
altered by the derived class
6. Overriding--With inheritance, we will be able to override the methods of the base class
so that meaningful implementation of the base class method can be designed in the
derived class.
Disadvantages:-
4
object-oriented languages) is the increased time/effort it takes the program to jump
44
through all the levels of overloaded classes. If a given class has ten levels
3
73
of abstraction above it, then it will essentially take ten jumps to run through a function
26
defined in each of those classes
07
p
ap
2. Main disadvantage of using inheritance is that the two classes (base and inherited
ts
class) get tightly coupled.
ha
W
This means one cannot be used independent of each other.
3. Also with time, during maintenance adding new features both base as well as derived
classes are required to be changed. If a method signature is changed then we will be
affected in both cases (inheritance & composition)
4. If a method is deleted in the "super class" or aggregate, then we will have to re-factor
in case of using that method. Here things can get a bit complicated in case of
inheritance because our programs will still compile, but the methods of the subclass
will no longer be overriding superclass methods. These methods will become
independent methods in their own right.
Implementation of Inheritance
Following are attributes observed in the implementation of inheritance
Base & Derived Classes:
A class can be derived from more than one classes, which means it can inherit data and
functions from multiple base classes. To define a derived class, we use a class
derivation list to specify the base class(es). A class derivation list names one or more
base classes and has the form:
class derived-class: access-specifier base-class
Where access-specifier is one of public, protected, or private, and base-class is the
name of a previously defined class. If the access-specifier is not used, then it is private
by default.
Consider a base class Shape and its derived class Rectangle as follows:
#include <iostream>
// Base class
class Shape
{
public:
void setWidth(int w)
{
width = w;
}
void setHeight(int h)
{
height = h;
4
44
}
protected:
3
73
int width;
26
int height;
07
};
p
ap
// Derived class
ts
class Rectangle: public Shape
ha
W
{
public:
int getArea()
{
return (width * height);
}
};
int main(void)
{
Rectangle Rect;
Rect.setWidth(5);
Rect.setHeight(7);
return 0;
}
When the above code is compiled and executed, it produces the following result:
Total area: 35
A derived class inherits all base class methods with the following exceptions:
Constructors, destructors and copy constructors of the base class.
Overloaded operators of the base class.
4
44
The friend functions of the base class.
3
73
26
When deriving a class from a base class, the base class may be inherited through
07
public, protected or private inheritance. The type of inheritance is specified by the
p
ap
access-specifier as explained above.
ts
ha
We hardly use protected or private inheritance, but public inheritance is commonly
W
used. While using different type of inheritance, following rules are applied:
Public Inheritance: When deriving a class from a public base class, public
members of the base class become public members of the derived class and
protected members of the base class become protected members of the derived
class. A base class's private members are never accessible directly from a
derived class, but can be accessed through calls to the public and protected
members of the base class.
Protected Inheritance: When deriving from a protected base class, public and
protected members of the base class become protected members of the derived
class.
Private Inheritance: When deriving from a private base class, public and
protected members of the base class become private members of the derived
class.
Concepts in inheritance
Single Inheritance is method in which a derived class has only one base class.
Example:
#include <iostream.h> class Value
{
protected:
int val;
public:
void set_values (int a)
{ val=a;}
}; class Cube: public Value
{
public:
int cube()
{ return (val*val*val); }
}; int main ()
{
Cube cub;
cub.set_values (5);
cout << "The Cube of 5 is::" << cub.cube() << endl;
return 0;
}
4
44
3
Result:
73
The Cube of 5 is:: 125
26
07
p
ap
ts
ha
Multiple inheritance is achieved whenever more than one class acts as base classes for other
W
classes. This makes the members of the base classes accessible in the derived class, resulting
in better integration and broader re-usability.
example:
#include <iostream>
using namespace std;
class Cpolygon
{
protected:
int width, height;
public:
void input_values (int one, int two)
{
width=one;
height=two;
}
};
class Cprint
{
public:
void printing (int output);
};
int main ()
4
44
{
Crectangle rectangle;
3
73
Ctriangle triangle;
26
rectangle.input_values (2,2);
07
triangle.input_values (2,2);
rectangle.printing (rectangle.area());
p
ap
triangle.printing (triangle.area());
ts
return 0;
ha
}
W
Note:the two public statements in the Crectangle class and Ctriangle class.
A non-member function can access the private and protected members of a class if it is
declared a friend of that class. That is done by including a declaration of this external function
within the class, and preceding it with the keyword friend:
// friend functions
#include <iostream>
using namespace std;
class Rectangle {
int width, height;
public:
Rectangle() {}
Rectangle (int x, int y) : width(x), height(y) {}
int area() {return width * height;}
friend Rectangle duplicate (const Rectangle&);
};
int main () {
Rectangle foo;
Rectangle bar (2,3);
foo = duplicate (bar);
cout << foo.area() << '\n';
return 0;
}
4
able to access the members width and height (which are private) of different objects of
44
type Rectangle.
3
73
26
Friend classes
07
Similar to friend functions, a friend class is a class whose members have access to the private
p
or protected members of another class:
ap
// friend class
ts
ha
#include <iostream>
W
using namespace std;
class Square;
class Rectangle {
int width, height;
public:
int area ()
{return (width * height);}
void convert (Square a);
};
class Square {
friend class Rectangle;
private:
int side;
public:
Square (int a) : side(a) {}
};
int main () {
Rectangle rect;
Square sqr (4);
rect.convert(sqr);
cout << rect.area();
return 0;
}
In this example, class Rectangle is a friend of class Square allowing Rectangle's member
functions to access private and protected members of Square. More concretely, Rectangle
accesses the member variable Square::side, which describes the side of the square.
Pointers to objects
A variable that holds an address value is called a pointer variable or simply pointer.
Pointer can point to objects as well as to simple data types and arrays. sometimes we don’t
know, at the time that we write the program , how many objects we want to creat. when this is
the case we can use new to create objects while the program is running. new returns a pointer
to an unnamed objects. Let’s see the example of student that will clear your idea about this
topic
4
member functions and member variables.
44
Defining a pointer of class type
3
73
We can define pointer of class type, which can be used to point to class objects.
26
class Simple
07
{
p
ap
public:
ts
int a;
ha
};
W
int main()
{
Simple obj;
Simple* ptr; // Pointer of class type
ptr = &obj;
Object.*pointerToMember
ObjectPointer->*pointerToMember
4
44
class Data
3
73
{
26
public:
07
int a;
p
void print() { cout << "a is="<< a; }
ap
ts
};
ha
W
int main()
{
Data d, *dp;
dp = &d; // pointer to object
d.*ptr=10;
d.print();
dp->*ptr=20;
dp->print();
}
The syntax is very tough, hence they are only used under special circumstances.
class Data
{ public:
int f (float) { return 1; }
};
int main(0
{
fp2 = &Data::f; // Assignment inside main()
4
44
}
3
73
Some Points to remember
26
07
p
1. You can change the value and behaviour of these pointers on runtime. That
ap
ts
means, you can point it to other member function or member variable.
ha
W
2. To have pointer to data member and member functions you need to make them
public.
Derived classes do not inherit constructors or destructors from their base classes, but
they do call the constructor and destructor of base classes. Destructors can be declared
with the keyword virtual.
Constructors are also called when local or temporary class objects are created, and
destructors are called when local or temporary objects go out of scope.
Constructor and Destructor invoking sequence with inheritance
Example Program
class Base
{
public:
Base ( )
{
cout << "Inside Base constructor" << endl;
}
~Base ( )
{
cout << "Inside Base destructor" << endl;
}
};
public:
Derived ( )
{
4
44
cout << "Inside Derived constructor" << endl;
}
3
73
26
~Derived ( )
07
{
cout << "Inside Derived destructor" << endl;
p
ap
}
ts
ha
};
W
void main( )
{
Derived x;
}
So, here is what the output of the code above would look like:
Inside Base constructor
Inside Derived constructor
Inside Derived destructor
Inside Base destructor
Base class constructors and derived class destructors are called first
In the code above, when the object "x" is created, first the Base class constructor is
called, and after that the Derived class constructor is called. Because the Derived class
inherits from the Base class, both the Base class and Derived class constructors will be
called when a Derived class object is created.
When the main function is finished running, the object x's destructor will get called
first, and after that the Base class destructor will be called.
Base class conversions
Upcasting is converting a derived-class reference or pointer to a base-class. In other
words, upcasting allows us to treat a derived type as though it were its base type. It is
always allowed for public inheritance, without an explicit type cast. This is a result of
the is-a relationship between the base and derived classes.
Here is the code dealing with shapes. We created Shape class, and derived Circle,
Square, and Triangle classes from the Shape class. Then, we made a member function
that talks to the base class:
void play(Shape& s)
{
s.draw();
s.move();
s.shrink();
....
}
4
44
The function speaks to any Shape, so it is independent of the specific type of object
3
73
that it's drawing, moving, and shrinking. If in some other part of the program we use
26
the play( ) function like below:
07
Circle c;
p
ap
Triangle t;
ts
Square sq;
ha
play(c);
W
play(t);
play(sq);
Let's check what's happening here. A Triangle is being passed into a function that is
expecting a Shape. Since a Triangle is a Shape, it can be treated as one by play(). That
is, any message that play() can send to a Shape a Triangle can accept.
Upcasting allows us to treat a derived type as though it were its base type. That's how
we decouple ourselves from knowing about the exact type we are dealing with.
Note that it doesn't say "If you're a Triangle, do this, if you're a Circle, do that, and so
on." If we write that kind of code, which checks for all the possible types of a Shape, it
will soon become a messy code, and we need to change it every time we add a new
kind of Shape. Here, however, we just say "You're a Shape, I know you can move(),
draw(), and shrink( ) yourself, do it, and take care of the details correctly."
The compiler and runtime linker handle the details. If a member function is virtual, then
when we send a message to an object, the object will do the right thing, even when
upcasting is involved.
Note that the most important aspect of inheritance is not that it provides member
functions for the new class, however. It's the relationship expressed between the new
class and the base class. This relationship can be summarized by saying, "The new
class is a type of the existing class."
class Parent {
public:
void sleep() {}
};
int main( )
{
Parent parent;
Child child;
4
44
return 0;
3
73
}
26
A Child object is a Parent object in that it inherits all the data members and member
07
functions of a Parent object. So, anything that we can do to a Parent object, we can do
p
ap
to a Child object. Therefore, a function designed to handle a Parent pointer (reference)
ts
ha
can perform the same acts on a Child object without any problems. The same idea
W
applies if we pass a pointer to an object as a function argument. Upcasting is transitive:
if we derive a Child class from Parent, then Parent pointer (reference) can refer to a
Parent or a Child object.
Upcasting can cause object slicing when a derived class object is passed by value as a
base class object, as in foo(Base derived_obj).
Downcasting
The opposite process, converting a base-class pointer (reference) to a derived-class
pointer (reference) is called downcasting. Downcasting is not allowed without an
explicit type cast. The reason for this restriction is that the is-a relationship is not, in
most of the cases, symmetric. A derived class could add new data members, and the
class member functions that used these data members wouldn't apply to the base class.
As in the example, we derived Child class from a Parent class, adding a member
function, gotoSchool(). It wouldn't make sense to apply the gotoSchool() method to a
Parent object. However, if implicit downcasting were allowed, we could accidentally
assign the address of a Parent object to a pointer-to-Child
Child *pChild = &parent; // actually this won't compile
// error: cannot convert from 'Parent *' to 'Child *'
and use the pointer to invoke the gotoSchool() method as in the following line.
pChild -> gotoSchool();
Because a Parent isn't a Child (a Parent need not have a gotoSchool() method), the
downcasting in the above line can lead to an unsafe operation.
C++ provides a special explicit cast called dynamic_cast that performs this conversion.
Downcasting is the opposite of the basic object-oriented rule, which states objects of a
derived class, can always be assigned to variables of a base class.
Dynamic Casting
4
44
3
The dynamic_cast operator answers the question of whether we can safely assign the
73
address of an object to a pointer of a particular type.
26
07
Here is a similar example to the previous one.
p
ap
#include <string>
ts
ha
class Parent {
W
public:
void sleep() {
}
};
int main( )
{
Parent *pParent = new Parent;
Parent *pChild = new Child;
4
Here is the syntax of dynamic_cast.
44
Child *p = dynamic_cast<Child *>(pParent)
3
73
This code is asking whether the pointer pParent can be type cast safely to the type
26
07
Child *.
p
ap
It returns the address of the object, if it can.
ts
ha
It returns 0, otherwise.
W
How do we use the dynamic_cast?
void f(Parent* p) {
Child *ptr = dynamic_cast<Child*>(p);
if(ptr) {
// we can safely use ptr
}
}
In the code, if (ptr) is of the type Child or else derived directly or indirectly from the
type Child, the dynamic_cast converts the pointer p to a pointer of type Child.
Otherwise, the expression evaluates to 0, the null pointer.
In other words, we want to check if we can use the passed in pointer p before we do
some operation on a child class object even though it's a pointer to base class.
"The need for dynamic_cast generally arises because we want perform derived class
operation on a derived class object, but we have only a pointer-or reference-to-base."
-Scott Meyers
Notes
downcast - A downcast is a cast from a base class to a class derived from that base
class.
cross-cast - A cross-cast is a cast between unrelated types (user-defined conversion)
Class Scope under Inheritance
Each class defines its own scope within which its members are defined. Under
inheritance, the scope of a derived class is nested inside the scope of its base classes. If
a name is unresolved within the scope of the derived class, the enclosing base-class
scopes are searched for a definition of that name.
The fact that the scope of a derived class nests inside the scope of its base classes can
be surprising. After all, the base and derived classes are defined in separate parts of our
program‘s text. However, it is this hierarchical nesting of class scopes that allows the
members ...
Overloading with Inheritance
Overloading doesn‘t work for derived class in C++ programming language. There is no
overload resolution between Base and Derived. The compiler looks into the scope of
Derived, finds the single function ―double f(double)‖ and calls it. It never disturbs with
4
the (enclosing) scope of Base. In C++, there is no overloading across scopes – derived
44
class scopes are not an exception to this general rule.
3
73
26
07
Inheritance relationship
p
Subclasses and superclasses can be understood in terms of the is a relationship. A subclass is a
ap
ts
more specific instance of a superclass. For example, an orange is a citrus fruit, which is a fruit.
ha
A shepherd is a dog, which is an animal.
W
If the is a relationship does not exist between a subclass and superclass, you should not use
inheritance.
Note: inheritance only reuses implementation and establishes a syntactic relationship, not
necessarily a semantic relationship (inheritance does not ensure behavioral subtyping). To
distinguish these concepts, subtyping is also known as interface inheritance, while inheritance
as defined here is known as implementation inheritance.
CHAPTER 6: POLYMORPHISM
Introduction to Polymorphism
Polymorphism is an object-oriented programming concept that refers to the ability of a
variable, function or object to take on multiple forms. A language that features
polymorphism allows developers to program in the general rather than program in the
specific.
In a programming language that exhibits polymorphism, objects of classes belonging to the
same hierarchical tree (i.e. inherited from a common base class) may possess functions
bearing the same name, but each having different behaviors.
As an example, let us assume there is a base class named Animals from which the
subclasses Horse, Fish and Bird are derived. Let us also assume that the Animals class
has a function named Move, which is inherited by all subclasses mentioned. With
4
polymorphism, each subclass may have its own way of implementing the function. So,
44
for example, when the Move function is called in an object of the Horse class, the
3
73
function might respond by displaying trotting on the screen. On the other hand, when
26
the same function is called in an object of the Fish class, swimming might be displayed
07
on the screen. In the case of a Bird object, it may be flying.
p
ap
ts
In effect, polymorphism trims down the work of the developer because he can now
ha
create a sort of general class with all the attributes and behaviors that he envisions for
W
it. When the time comes for the developer to create more specific subclasses with
certain unique attributes and behaviors, the developer can simply alter code in the
specific portions where the behaviors will differ. All other portions of the code can be
left as is.
Advantages/importance of Polymorphism
When an object has a reference to another, it can invoke methods on that object reference
without knowing, or caring, what the implementation is.
Why Polymorphism?
Note
•Substitutability means, the type of the variable does not have to match with the type of the
value assigned to that variable.
•Substitutability cannot be achieved in conventional languages in C, but can be achieved in
Object Oriented languages like Java.
•We have already seen the concept of “Assigning a subclass object to superclass variable or
reference”. This is called substitutability. Here I am substituting the superclass object with the
object of subclass.
4
44
3
73
26
07
p
ap
ts
ha
W
Discussion
The word polymorphism means having many forms. Typically, polymorphism occurs
when there is a hierarchy of classes and they are related by inheritance.
C++ polymorphism means that a call to a member function will cause a different
function to be executed depending on the type of object that invokes the function.
Consider the following example where a base class has been derived by other two
classes:
#include <iostream>
using namespace std;
class Shape {
protected:
int width, height;
public:
Shape( int a=0, int b=0)
{
width = a;
height = b;
}
int area()
{
cout << "Parent class area :" <<endl;
return 0;
}
};
class Rectangle: public Shape{
public:
Rectangle( int a=0, int b=0):Shape(a, b) { }
int area ()
{
cout << "Rectangle class area :" <<endl;
return (width * height);
}
4
44
};
class Triangle: public Shape{
3
73
public:
Triangle( int a=0, int b=0):Shape(a, b) { }
26
int area ()
07
{
p
cout << "Triangle class area :" <<endl;
ap
return (width * height / 2);
ts
ha
}
W
};
// Main function for the program
int main( )
{
Shape *shape;
Rectangle rec(10,7);
Triangle tri(10,5);
return 0;
}
When the above code is compiled and executed, it produces the following result:
The reason for the incorrect output is that the call of the function area() is being set
once by the compiler as the version defined in the base class. This is called static
resolution of the function call, or static linkage - the function call is fixed before the
program is executed. This is also sometimes called early binding because the area()
function is set during the compilation of the program.
But now, let's make a slight modification in our program and precede the declaration of
area() in the Shape class with the keyword virtual so that it looks like this:
class Shape {
protected:
int width, height;
public:
Shape( int a=0, int b=0)
{
width = a;
height = b;
}
virtual int area()
{
cout << "Parent class area :" <<endl;
return 0;
}
};
4
44
After this slight modification, when the previous example code is compiled and
3
73
executed, it produces the following result:
26
07
Rectangle class area
p
Triangle class area
ap
ts
ha
This time, the compiler looks at the contents of the pointer instead of it's type. Hence,
W
since addresses of objects of tri and rec classes are stored in *shape the respective
area() function is called.
As you can see, each of the child classes has a separate implementation for the function
area(). This is how polymorphism is generally used. You have different classes with a
function of the same name, and even the same parameters, but with different
implementations.
4
Information Hiding is achieved in Object Oriented Programming using the following
44
principles,
3
73
· All information related to an object is stored within the object
26
· It is hidden from the outside world
07
· It can only be manipulated by the object itself
p
ap
ts
ha
Advantages of Information Hiding
W
Following are two major advantages of information hiding. It simplifies our Object
Oriented Model:
As we saw earlier that our object oriented model only had objects and their interactions
hiding implementation details so it makes it easier for everyone to understand our
object oriented model. It is a barrier against change propagation. As implementation of
functions is limited to our class and we have only given the name of functions to user
along with description of parameters so if we change implementation of function it
doesn‘t affect the object oriented model.
We can achieve information hiding using Encapsulation and Abstraction, so we see
these two concepts in detail now.
Encapsulation means “we have enclosed all the characteristics of an object in the
object itself”.
Encapsulation and information hiding are much related concepts (information hiding is
achieved using Encapsulation). We have seen in previous lecture that object
characteristics include data members and behavior of the object in the form of
functions. So we can say that Data and Behavior are tightly coupled inside an object
and both the information structure and implementation details of its operations are
hidden from the outer world.
Examples of Encapsulation
Consider the same example of object Ali of previous lecture we described it as follows.
Ali
Characteristics (attributes)
· Name
· Age
Behavior (operations)
· Walks
· Eats
You can see that Ali stores his personal information in itself and its behavior is also
implemented in it. Now it is up to object Ali whether he wants to share that information
with outside world or not. Same thing stands for its behavior if some other object in real
life wants to use his behavior of walking it can not use it without the permission of Ali.
So we say that attributes and behavior of Ali are encapsulated in it. Any other object
don‘t know about these things unless Ali share this information with that object through
an interface. Same concept also applies to phone which has some data and behavior of
showing that data to user we can only access the information stored in the phone if
4
phone interface allow us to do so.
44
3
73
Advantages of Encapsulation
26
The following are the main advantages of Encapsulation,
07
p
1. Simplicity and clarity
ap
ts
As all data and functions are stored in the objects so there is no data or function around
ha
in program that is not part of any object and is this way it becomes very easy to
W
understand the purpose of each data member and function in an object.
2. Low complexity
As data members and functions are hidden in objects and each object has a specific
behavior so there is less complexity in code there will be no such situations that a
functions is using some other function and that functions is using some other function.
3. Better understanding
Everyone will be able to understand whole scenario by simple looking into object
diagrams without any issue as each object has specific role and specific relation with
other objects.
class Shape {
protected:
int width, height;
public:
Shape( int a=0, int b=0)
{
width = a;
height = b;
}
// pure virtual function
virtual int area() = 0;
};
The = 0 tells the compiler that the function has no body and above virtual function will
be called pure virtual function.
4
44
3
Data Abstraction
73
Data abstraction refers to, providing only essential information to the outside world and
26
07
hiding their background details, i.e., to represent the needed information in program
p
without presenting the details.
ap
ts
ha
Data abstraction is a programming (and design) technique that relies on the separation
W
of interface and implementation.
Let's take one real life example of a TV, which you can turn on and off, change the
channel, adjust the volume, and add external components such as speakers, VCRs, and
DVD players, BUT you do not know its internal details, that is, you do not know how it
receives signals over the air or through a cable, how it translates them, and finally
displays them on the screen.
Thus, we can say a television clearly separates its internal implementation from its
external interface and you can play with its interfaces like the power button, channel
changer, and volume control without having zero knowledge of its internals.
Now, if we talk in terms of C++ Programming, C++ classes provides great level
of data abstraction. They provide sufficient public methods to the outside world to
play with the functionality of the object and to manipulate object data, i.e., state without
actually knowing how class has been implemented internally.
For example, your program can make a call to the sort() function without knowing
what algorithm the function actually uses to sort the given values. In fact, the
underlying implementation of the sorting functionality could change between releases
of the library, and as long as the interface stays the same, your function call will still
work.
In C++, we use classes to define our own abstract data types (ADT). You can use
the cout object of class ostream to stream data to standard output like this:
#include <iostream>
using namespace std;
int main( )
.{
cout << "Hello C++" <<endl;
return 0;
}
Here, you don't need to understand how cout displays the text on the user's screen. You
need to only know the public interface and the underlying implementation of cout is
free to change.
4
44
Members defined with a private label are not accessible to code that uses the
3
73
class. The private sections hide the implementation from code that uses the type.
26
07
There are no restrictions on how often an access label may appear. Each access label
p
specifies the access level of the succeeding member definitions. The specified access
ap
level remains in effect until the next access label is encountered or the closing right
ts
ha
brace of the class body is seen.
W
Benefits of Data Abstraction:
Data abstraction provides two important advantages:
Class internals are protected from inadvertent user-level errors, which might
corrupt the state of the object.
The class implementation may evolve over time in response to changing
requirements or bug reports without requiring change in user-level code.
By defining data members only in the private section of the class, the class author is
free to make changes in the data. If the implementation changes, only the class code
needs to be examined to see what affect the change may have. If data are public, then
any function that directly accesses the data members of the old representation might be
broken.
class Adder{
public:
// constructor
Adder(int i = 0)
{
total = i;
}
// interface to outside world
void addNum(int number)
{
total += number;
}
// interface to outside world
int getTotal()
{
return total;
};
private:
// hidden data from outside world
int total;
};
int main( )
{
Adder a;
a.addNum(10);
4
a.addNum(20);
44
a.addNum(30);
3
73
cout << "Total " << a.getTotal() <<endl;
26
return 0;
07
}
p
ap
ts
When the above code is compiled and executed, it produces the following result:
ha
W
Total 60
Above class adds numbers together, and returns the sum. The public
members addNum and getTotalare the interfaces to the outside world and a user needs
to know them to use the class. The private member total is something that the user
doesn't need to know about, but is needed for the class to operate properly.
Designing Strategy:
Abstraction separates code into interface and implementation. So while designing your
component, you must keep interface independent of the implementation so that if you
change underlying implementation then interface would remain intact.
In this case whatever programs are using these interfaces, they would not be impacted
and would just need a recompilation with the latest implementation.
Data Encapsulation
All C++ programs are composed of the following two fundamental elements:
Program statements (code): This is the part of a program that performs actions
and they are called functions.
Program data: The data is the information of the program which affected by the
program functions.
Encapsulation is an Object Oriented Programming concept that binds together the data
and functions that manipulate the data, and that keeps both safe from outside
interference and misuse. Data encapsulation led to the important OOP concept of data
hiding.
Data encapsulation is a mechanism of bundling the data, and the functions that use
them and data abstraction is a mechanism of exposing only the interfaces and hiding
the implementation details from the user.
C++ supports the properties of encapsulation and data hiding through the creation of
user-defined types, called classes. We already have studied that a class can
contain private, protected and publicmembers. By default, all items defined in a class
are private. For example:
class Box
{
public:
double getVolume(void)
{
return length * breadth * height;
}
private:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
4
44
};
3
73
The variables length, breadth, and height are private. This means that they can be
26
accessed only by other members of the Box class, and not by any other part of your
07
program. This is one way encapsulation is achieved.
p
To make parts of a class public (i.e., accessible to other parts of your program), you
ap
ts
must declare them after the public keyword. All variables or functions defined after the
ha
public specifier are accessible by all other functions in your program.
W
Making one class a friend of another exposes the implementation details and reduces
encapsulation. The ideal is to keep as many of the details of each class hidden from all
other classes as possible.
class Adder{
public:
// constructor
Adder(int i = 0)
{
total = i;
}
// interface to outside world
void addNum(int number)
{
total += number;
}
// interface to outside world
int getTotal()
{
return total;
};
private:
// hidden data from outside world
int total;
};
int main( )
{
Adder a;
a.addNum(10);
a.addNum(20);
a.addNum(30);
When the above code is compiled and executed, it produces the following result:
Total 60
4
Above class adds numbers together, and returns the sum. The public
44
members addNum and getTotalare the interfaces to the outside world and a user needs
3
73
to know them to use the class. The private member total is something that is hidden
26
from the outside world, but is needed for the class to operate properly.
07
p
ap
Designing Strategy:
ts
ha
Most of us have learned through bitter experience to make class members private by
W
default unless we really need to expose them. That's just good encapsulation.
This wisdom is applied most frequently to data members, but it applies equally to all
members, including virtual functions.
Classes that can be used to instantiate objects are called concrete classes.
4
44
// Base class
3
class Shape
73
{
26
public:
07
// pure virtual function providing interface framework.
p
virtual int getArea() = 0;
ap
void setWidth(int w)
ts
{
ha
width = w;
W
}
void setHeight(int h)
{
height = h;
}
protected:
int width;
int height;
};
// Derived classes
class Rectangle: public Shape
{
public:
int getArea()
{
return (width * height);
}
};
class Triangle: public Shape
{
public:
int getArea()
{
return (width * height)/2;
}
};
int main(void)
{
Rectangle Rect;
Triangle Tri;
Rect.setWidth(5);
Rect.setHeight(7);
// Print the area of the object.
cout << "Total Rectangle area: " << Rect.getArea() << endl;
Tri.setWidth(5);
Tri.setHeight(7);
// Print the area of the object.
cout << "Total Triangle area: " << Tri.getArea() << endl;
return 0;
}
When the above code is compiled and executed, it produces the following result:
4
44
You can see how an abstract class defined an interface in terms of getArea() and two
3
73
other classes implemented same function but with different algorithm to calculate the
26
area specific to the shape.
07
p
ap
Designing Strategy:
ts
An object-oriented system might use an abstract base class to provide a common and
ha
standardized interface appropriate for all the external applications. Then, through
W
inheritance from that abstract base class, derived classes are formed that all operate
similarly.
The capabilities (i.e., the public functions) offered by the external applications are
provided as pure virtual functions in the abstract base class. The implementations of
these pure virtual functions are provided in the derived classes that correspond to the
specific types of the application.
This architecture also allows new applications to be added to a system easily, even after
the system has been defined.
CHAPTER 7: CONSTRUCTORS AND
DESTRUCTORS
Definition of 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
4
44
same as the name of the class, and contructors never have return type.
3
73
Constructors can be defined either inside the class definition or outside class definition
26
07
using class name and scope resolution‖::‖ operator.
p
ap
ts
ha
class A
W
{
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;
}
4
Output : 10
44
3
73
In this case, as soon as the object is created the constructor is called which initializes its
26
data members.
07
p
ap
A default constructor is so important for initialization of object members, that even if
ts
we do not define a constructor explicitly, the compiler will provide a default
ha
W
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);
4
cout << c1.side;
44
cout << c2.side;
3
73
cout << c3.side;
26
}
07
p
OUTPUT : 10 20 30
ap
ts
ha
W
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
4
overloading the constructors.
44
3
73
One more important thing, if you define any constructor explicitly, then the compiler
26
will not provide default constructor and you will have to define it yourself.
07
p
ap
In the above case if we write Student S; in main(), it will lead to a compile time
ts
error, because we haven't defined default constructor, and compiler will not provide its
ha
default constructor because we have defined other parameterized constructors.
W
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();
};
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
4
44
3
73
26
Implementation of constructors and Destructors
07
Single Definition for both Default and Parameterized Constructor
p
ap
In this example we will use default argument to have a single definition for both
ts
defualt and parameterized constructor.
ha
W
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.
CHAPTER 8: OPERATOR OVERLOADING
Meaning and importance of operator overloading
Operator overloading is an important concept in C++. It is a type of polymorphism in
which an operator is overloaded to give user defined meaning to it. Overloaded
operator is used to perform operation on user-defined data type. For example '+'
operator can be overloaded to perform addition on various data types, like for Integer,
String(concatenation) etc.
4
44
3
73
26
07
Almost any operator can be overloaded in C++. However there are few operator which
p
ap
can not be overloaded. Operator that are not overloaded are follows
ts
ha
1. scope operator - ::
W
2. sizeof
3. member selector - .
4. member pointer selector - *
5. ternary operator - ?:
4
some examples to learn more about operator overloading. All the examples are closely
44
connected.
3
73
Overloading Arithmetic Operator
26
Arithmetic operator are most commonly used operator in C++. Almost all arithmetic
07
operator can be overloaded to perform arithmetic operation on user-defined data type.
p
ap
In the below example we have overridden the + operator, to add to Time (hh:mm:ss)
ts
objects.
ha
W
Example: overloading '+' Operator to add two time object
#include< iostream.h>
#include< conio.h>
class time
{
int h,m,s;
public:
time()
{
h=0, m=0; s=0;
}
void getTime();
void show()
{
cout<< h<< ":"<< m<< ":"<< s;
}
time operator+(time); //overloading '+' operator
};
time time::operator+(time t1) //operator function
{
time t;
int a,b;
a=s+t1.s;
t.s=a%60;
b=(a/60)+m+t1.m;
t.m=b%60;
t.h=(b/60)+h+t1.h;
t.h=t.h%12;
return t;
}
void time::getTime()
{
cout<<"\n Enter the hour(0-11) ";
cin>>h;
cout<<"\n Enter the minute(0-59) ";
cin>>m;
cout<<"\n Enter the second(0-59) ";
cin>>s;
}
4
void main()
44
{
3
73
clrscr();
26
time t1,t2,t3;
07
cout<<"\n Enter the first time ";
p
ap
t1.getTime();
ts
cout<<"\n Enter the second time ";
ha
W
t2.getTime();
t3=t1+t2; <font color="green">//adding of two time object using '+' operator
cout<<"\n First time ";
t1.show();
cout<<"\n Second time ";
t2.show();
cout<<"\n Sum of times ";
t3.show();
getch();
}
You have seen above that operator is overloaded with ostream class object
cout to print primitive type value output to the screen. Similarly you can overload
operator in your class to print user-defined type to screen. For example we will
overload in time class to display time object using cout .
time t1(3,15,48);
cout << t1;
NOTE: When the operator does not modify its operands, the best way to overload the
operator is via friend function.
4
44
hr=0, min=0; sec=0;
3
73
}
26
time(int h,int m, int s)
07
{
p
hr=h, min=m; sec=s;
ap
ts
}
ha
friend ostream& operator << (ostream &out, time &tm); //overloading '<<'
W
operator
};
ostream& operator<< (ostream &out, time &tm) //operator function
{
out << "Time is " << tm.hr << "hour : " << tm.min << "min : " << tm.sec << "sec";
return out;
}
void main()
{
time tm(3,15,45);
cout << tm;
}
Output
Time is 3 hour : 15 min : 45 sec
Example
class time
{
int hr,min,sec;
public:
time()
{
hr=0, min=0; sec=0;
}
time(int h,int m, int s)
{
hr=h, min=m; sec=s;
}
friend bool operator==(time &t1, time &t2); //overloading '==' operator
};
bool operator== (time &t1, time &t2) //operator function
{
return ( t1.hr == t2.hr &&
4
t1.min == t2.min &&
44
t1.sec == t2.sec );
3
73
}
26
Copy constructor Vs. Assignment operator
07
Assignment operator is used to copy the values from one object to another already
p
ap
existing object. For example
ts
time tm(3,15,45); //tm object created and initialized
ha
W
time t1; //t1 object created
t1 = tm; //initializing t1 using tm
Copy constructor is a special constructor that initializes a new object from an existing
object.
time tm(3,15,45); //tm object created and initialized
time t1(tm); //t1 object created and initialized using tm object
Note
Constructor/destructor
Constructors are called automatically by the compiler when defining class objects. The
destructor’s are called when a class object goes out of scope.
Default constructor is a constructor that can be called without having to provide any
arguments, irrespective of whether the constructor is auto-generated or used-defined.
Like any other function, a constructor can also be overloaded with different versions taking
different parameters: with a different number of parameters and/or parameters of different
types. The compiler will automatically call the one whose parameters match the arguments
Operators are binary or unary.
Unary Operators has only one operand. The operation takes place using a single operand. The
Unary Operators are ++,--,&,*(indirection),-(positive),-(neg... etc.
Unary operators have precedence over binary operators.
Binary operators (”bi” as in “two”) have two operands. In “A*B” the * operator has two
operands: A and B. In “!B” the “!” operator (meaning boolean NOT) has only one operand, and
is therefore a unary operator. The “-” and “+” operators can be both binary and unary, in “-4″
or “+4″ it denotes a negative or a positive number, in “0-4″ it acts as the subtraction operator.
1) Only built-in operators can be overloaded. New operators can not be created.
2) Arity of the operators (number of arguments or operands the function or operation
accepts) cannot be changed.
4
3) Precedence and associativity of the operators cannot be changed.
44
4) Overloaded operators cannot have default arguments except the function call operator
3
73
() which can have default arguments.
26
5) Operators cannot be overloaded for built in types only. At least one operand must be
07
p
used defined type.
ap
ts
6) Assignment (=), subscript (*+), function call (“()”), and member selection (->) operators
ha
must be defined as member functions
W
7) Except the operators specified in point 6, all other operators can be either member
functions or a non-member functions.
8) Some operators like (assignment)=, (address)& and comma (,) are by default
overloaded.
1. The overloaded new operator receives a parameter num of type size_t. This is
the number of bytes of memory to be allocated. The compiler calculates and
sends this to us!
2. The return type of the overloaded new must be void*. It is expected to return a
pointer to the beginning of the block of memory allocated. Note that after our
overloaded new returns, the compiler then automatically calls the constructor
also as applicable.
3. The overloaded delete operator receives a parameter ptr of type void*. This
is the pointer the user is trying to delete.
4
44
5. In this sample implementation, since the focus is only on showing how to
3
73
overload, we have done the memory allocation and deallocation using malloc()
26
and free() functions. In real life situations, we would prefer to do something
07
more than this!
p
ap
Deleting an array of objects is not the same as deleting an object, i.e. delete[] ptr;
ts
ha
and delete ptr; are totally different and involve different operators! In case you are
W
interested in overloading delete for an array, use the following:
void operator delete[](void *ptr)
{
free(ptr);
}
Examples
If the reference operator is used you will get the “address of” a variable.
ptr_p = &x;
If the dereference operator is used you will get the “value pointed by” a pointer.
x = 5;
ptr_p = &x;
cout << *ptr_p;
Meaning: print (or put into the stream) the value pointed by ptr_p. (It will print the contents
of integer x.)
4
44
3
73
26
07
p
ap
ts
ha
W
CHAPTER 9: FILE ORGANISATION
Introduction to File organization
Files contain computer records which can be documents or information which is stored
in a certain way for later retrieval.
File organization refers primarily to the logical arrangement of data (which can itself be
organized in a system of records with correlation between the fields/columns) in a file
system. It should not be confused with the physical storage of the file in some types of
storage media. There are certain basic types of computer file, which can include files
stored as blocks of data and streams of data, where the information streams out of the
file while it is being read until the end of the file is encountered.
4
file organization is a design decision, hence it must be done having in mind the
44
achievement of good performance with respect to the most likely usage of the file. The
3
73
criteria usually considered important are:
26
07
1. Fast access to single record or collection of related recors.
p
ap
2. Easy record adding/update/removal, without disrupting .
ts
ha
W
3. Storage efficiency.
4. Redundance as a warranty against data corruption.
(a) A file
4
44
3
Opening a File:
73
A file must be opened before you can read from it or write to it. Either the ofstream or
26
07
fstream object may be used to open a file for writing and ifstream object is used to
p
open a file for reading purpose only.
ap
ts
Following is the standard syntax for open() function, which is a member of fstream,
ha
ifstream, and ofstream objects.
W
void open(const char *filename, ios::openmode mode);
Here, the first argument specifies the name and location of the file to be opened and the
second argument of the open() member function defines the mode in which the file
should be opened.
Mode Flag Description
ios::app Append mode. All output to that file to be appended to the end.
Open a file for output and move the read/write control to the end of
ios::ate
the file.
ios::in Open a file for reading.
ios::out Open a file for writing.
If the file already exists, its contents will be truncated before
ios::trunc
opening the file.
You can combine two or more of these values by ORing them together. For example if
you want to open a file in write mode and want to truncate it in case it already exists,
following will be the syntax:
ofstream outfile;
outfile.open("file.dat", ios::out | ios::trunc );
Similar way, you can open a file for reading and writing purpose as follows:
fstream afile;
afile.open("file.dat", ios::out | ios::in );
Closing a File
When a C++ program terminates it automatically closes flushes all the streams, release
all the allocated memory and close all the opened files. But it is always a good practice
that a programmer should close all the opened files before program termination.
Following is the standard syntax for close() function, which is a member of fstream,
ifstream, and ofstream objects.
void close();
Writing to a File:
While doing C++ programming, you write information to a file from your program
using the stream insertion operator (<<) just as you use that operator to output
information to the screen. The only difference is that you use an ofstream or fstream
object instead of the cout object.
4
44
Reading from a File:
3
73
You read information from a file into your program using the stream extraction
26
operator (>>) just as you use that operator to input information from the keyboard. The
07
only difference is that you use an ifstream or fstream object instead of the cin object.
p
ap
ts
ha
Read & Write Example:
W
Following is the C++ program which opens a file in reading and writing mode. After
writing information inputted by the user to a file named afile.dat, the program reads
information from the file and outputs it onto the screen:
#include <fstream>
#include <iostream>
using namespace std;
int main ()
{
char data[100];
// again read the data from the file and display it.
infile >> data;
cout << data << endl;
4
44
// close the opened file.
3
73
infile.close();
26
07
return 0;
p
}
ap
ts
When the above code is compiled and executed, it produces the following sample input
ha
and output:
W
$./a.out
Writing to the file
Enter your name: Zara
Enter your age: 9
Reading from the file
Zara
9
Above examples make use of additional functions from cin object, like getline()
function to read the line from outside and ignore() function to ignore the extra
characters left by previous read statement.
4
44
3
73
26
07
p
ap
ts
ha
W
CHAPTER 10: EMERGING TRENDS IN OOP
The major goals of object-orientation are to produce well-structured software and to
build more extensible and reusable systems. It seems that the second goal is more
important because it is more difficult to achieve and there remains more work to be
done. We believe that the following areas of OO will most prominently contribute to
this goal in the future:
Frameworks
Frameworks have been recognized as one of the most promising OO technologies
because they provide large scale reuse. The reuse of individual classes, while helpful,
will not bring significant productivity leaps. Only the reuse of taylorable systems as a
whole will lead to noticeable results. Although frameworks are widely used today, there
remain many open problems to be tackled, for example:
How can a framework be designed systematically?
Current frameworks are developed in a rather ad-hoc manner by comparing existing
4
44
systems and extracting their common features. This process is iterative and good
3
73
frameworks are only obtained after many iterations.
26
Why is framework design not more systematic? One reason is that current design
07
methods hardly apply to frameworks. Their aim is to model one specific problem
p
but not a set of various similar problems. Traditionally, the main question is "what
ap
ts
are the objects in a given situation?" wheras for frameworks the main question
ha
should be "what is to be kept flexible so that it fits several situations?". We need
W
special methods and guidelines for designing frameworks. Such methods could be
based on design patterns that help putting together a framework from templates of
proven OO knowledge.
4
44
3
o Finding new patterns and unifying existing ones.
73
26
o Finding better notations to describe patterns, their structure, their
07
dynamic behavior, and their integration into larger systems. Beside graphical
p
ap
notations, formal pattern languages might be a promising solution.
ts
ha
o Integrating patterns with programming languages. If a programming
W
language could express and check the correct use of design patterns,
programming could be raised to a higher level and source code could become
better understandable.
Distributed Objects
Distributed objects that operate in a concurrent and active way have been a research
topic in the OO community for a long time because the metaphor of communicating
objects lends itself to distribution well. With the success of the Internet and appropriate
programming languages such as Java this topic has gained additional relevance. How
can intelligent and active objects improve the use of the Net? How can security
problems be solved that result from such a distribution? How can objects in
heterogeneous environments (different computers, languages, and operating systems)
cooperate effectively?
o Dynamic extensibility.
Extensibility is one of the virtues of object-orientation. Yet many systems are
restricted by static extensibility. They can only be extended by interrupting their
use, relinking and reloading them. Relinking requires that the individual object
files are available, which is usually not the case in commercial systems. In
contrast, dynamic languages such as Smalltalk and Self allow extending a system
at run time without disrupting its use. This should also become possible in
compiled languages and systems (It is already the case in Java or Oberon, for
4
44
example.)
3
73
Finally, an important challenge will be to bring all these techniques to the mainstream
26
software industry. While many software products claim to be object-oriented, they
07
often just use an OO language or at best classes as a structuring aid. The idea of
p
ap
(custom-) extensible systems is not yet common in practice.
ts
ha
W