Compiled By: Sandeep Sappal
Compiled By: Sandeep Sappal
1
13,Gulabchand ki Bagichi, Behind Jhawer Estate, Thatipur Gwl
Mob. : 9301123085, Ph. : 4062091
Compiled By: Sandeep Sappal
2
13,Gulabchand ki Bagichi, Behind Jhawer Estate, Thatipur Gwl
Mob. : 9301123085, Ph. : 4062091
Compiled By: Sandeep Sappal
3
13,Gulabchand ki Bagichi, Behind Jhawer Estate, Thatipur Gwl
Mob. : 9301123085, Ph. : 4062091
Compiled By: Sandeep Sappal
4
13,Gulabchand ki Bagichi, Behind Jhawer Estate, Thatipur Gwl
Mob. : 9301123085, Ph. : 4062091
Compiled By: Sandeep Sappal
5
13,Gulabchand ki Bagichi, Behind Jhawer Estate, Thatipur Gwl
Mob. : 9301123085, Ph. : 4062091
Compiled By: Sandeep Sappal
✓ Modular programming
✓ Structured programming
The primary motivation in each case is to eliminate the complexity of program and make
language more reliable and portable.
This is the most popular tech. Of 1980’s. POP employs top down programming approach where
a problem is viewed as a sequence of tasks to be performed. A number of functions or
procedures are written to attempt these tasks, Means this language is totally
function/procedural oriented.
Drawbacks of POP
1) Data move openly around the system and are there for vulnerable changes caused by
any function in the program.
2) As a programs grew larger, even the structured approach failed to show the
desired output in terms of bug free, easy to maintain and reusable program.
Object Oriented Programming (OOP) was invented to overcome the drawbacks of POP.
Every thing in this world is an Object and the human being in this real world is very close to
these objects because these objects are used by human beings. So if programming tech. Is
modeled as object oriented it is very easily to handled and understand by the programmers or
users. Thus this programming tech. is also kwon as real world/real time programming.
Oops treated the Data as a critical element and dose not allow it to flow freely in a program, it
binds the data more closely to the function which operate on it and protect it from accidental
modification in a data structure called class. This feature is called encapsulation.
✓ Function that operate on the data of an object are tied together in a data structure
✓ Data is hidden and cannot access by any external function even main
7
13,Gulabchand ki Bagichi, Behind Jhawer Estate, Thatipur Gwl
Mob. : 9301123085, Ph. : 4062091
Compiled By: Sandeep Sappal
Components of OOPS
✓ Classes:
Classes can be defined using keyword class. A class declaration is used to create a new
identifier kwon as object. The entire set of data and code of an object can be made a user
define type with the help of a class. Object are variable of the type class. Once class has been
define, we can create any number of objects belonging to that class. A class is thus a collection
of objects of similar types.
Note: 1) Classes are Logical Abstraction While Objects Have Physical Existence.
private:
public:
A class declaration is similar to struct declaration. The keyword class specifies, that what follows
is an abstract data of type <class name>. A class generally contains two types of member.
1) Private
2) Public
Members which declare private within the class can be accessed only within the class. On other
hand public members can be accessed from outside the class also.
Private members: This section is used to define abstract or hidden member. Members which
are declared in this section are totally hidden and can’t be accessed by any external function
even main(). Only the member function which are declared within the class can access these
members.
Public members: Members which are declared in this section can be accessed by any external
8
13,Gulabchand ki Bagichi, Behind Jhawer Estate, Thatipur Gwl
Mob. : 9301123085, Ph. : 4062091
Compiled By: Sandeep Sappal
✓ Objects:
Objects are instance of class. These are basic run time entities of object oriented programming
system. They may represent person, place, bank account etc.
Any Objects can be Identified by their behaviour and this particular behaviour assigns them a
unique name. State represent the nature of object.
✓ Objects are real world entities which contains data and process both.
✓ Objects take memory space in the memory and have associated address.
✓ When a program is executed, the objects interact by sending message to one another.
✓ For example, if “customer” and “account” are two objects in a program, then the
customer object may send a message to the account object requesting for bank balance.
Creating Objects:
Ex:
The wrapping up of data and function within a single unit(class) is known as encapsulation.
Encapsulation is the way to implement the data abstraction.
Data encapsulation is the most striking feature if the class. The data is not accessible to the
outside world, only those function which wrapped in the class can access it. These function are
interface between object data and the program. This insulation of the data from the direct
access by the program is called Data Hiding.
Abstraction refers to the act of representing essential features without including the
9
13,Gulabchand ki Bagichi, Behind Jhawer Estate, Thatipur Gwl
Mob. : 9301123085, Ph. : 4062091
Compiled By: Sandeep Sappal
background details of explanations. Classes uses the concept of data hiding means the member
which declare in private section of class can’t access by any external function.
Ex. To understand the abstraction lets take an example of car, you anly know the essential
feature of car like gear handling , steering handling, use of break and clutch etc.
But while driving a car you don’t know about the engine, gear, break, clutch, how it is
Internally working.
✓ Inheritance:
Inheritance is the process by which objects one class acquire the properties of objects of
another class.
1. Its capability to express the inheritance relationship which makes it ensure the closeness
with the real world models.
2. Another is the idea of reusability. Inheritance allows the addition of additional features
to an existing class without modifying it.
3. The third reason is its transitive nature. If a class A inherits properties of another class B,
then all subclass of A will automatically inherit the properties of B.
Vehicle
s
Car Bus
Rickshaw Cart
10
13,Gulabchand ki Bagichi, Behind Jhawer Estate, Thatipur Gwl
Mob. : 9301123085, Ph. : 4062091
Compiled By: Sandeep Sappal
The class whose properties are inherited, is called Base Class or Super Class and the class that
inherits these properties, is called Derived class or sub class.
Vehicles is the base class of automobiles and pulled vehicles, means both access the
properties of Vehicles. Car and bus are the sub class of automobiles. automobiles is the base
class of Car and Bus.
✓ Polymorphism:
Polymorphism is the another feature OOPS . Polymorphism is a Greek term, means the ability to
take more than one form. Polymorphism is also introduces reusability, reuse of same name or
operation for a different different purpose.
For Example if ‘+’ operator is used to add two numbers ,its also used to add two strings means a
‘+’ symbol by default is used to add two numbers but when it is reuse to add two strings then its
behaviours gets change and it introduces the concept of polymorphism .
Ex: A process DRAW is used to draw a rectangle, triangle ,circle etc .So here DRAW is process
which is reused for three purpose.
✓ Message Passing:
Ex. If two Banks(two objects) wants to establish communication the Message passing is used.
SBI RBI
11
13,Gulabchand ki Bagichi, Behind Jhawer Estate, Thatipur Gwl
Mob. : 9301123085, Ph. : 4062091
Compiled By: Sandeep Sappal
StaticMember Data.
A data member of a class can be qualified as static. the properties of a static member variable
are similar to that of a C static variable. A static member variable has certain special
characteristics. These are:
• It is initialized to zero when the first object of its class is created. No other initialization
is permitted.
• Only one copy of that member is created for the entire class and is shared by all the
objects of that class, no matter how many objects are created.
• It is visible only within the class, but its lifetime is the entire program.
Static variables are normally used to maintain values common to the entire class. For example,
a static data member can be used as a counter that records the occurrences of all the objects
Note that the type and scope of each static member variable must be defined outside the class
definition. This is necessary because the static data members are stored separately rather than
as a part of an object. Since they are associated with the class itself rather than with any class
object, they are also known as class variables.
Like static member variable, we can also have static member functions. A member function that
is declared static has the following properties:
• A static function can have access to only other static members (functions or variables)
declared in the same class.
• A static member function can be called using the class name (instead of its objects) as
follows:
Class-name :: function-name;
12
13,Gulabchand ki Bagichi, Behind Jhawer Estate, Thatipur Gwl
Mob. : 9301123085, Ph. : 4062091
Compiled By: Sandeep Sappal
Friendly functions
The function declaration should be preceded by the keyword friend the function is defined
elsewhere in the program like a normal C++ function A function can be declared as a friend in
any number of classes. A friend function, although not a member function, has full access rights
to the private member of the class.
▪ It is not in the scope of the class to which it has been declared as friend .
▪ Since it is not in the scope of the class, it cannot be called using the object of that
class.
▪ It can be invoked like a normal function without the help of any object.
▪ Unlike member function, it cannot access the member names directly and has to use
an object name and dot membership operator with each member name.(e. g .A. x)
▪ It can be declared either in the public or the private part of a class without affecting
its meaning.
Syntax
===
13
13,Gulabchand ki Bagichi, Behind Jhawer Estate, Thatipur Gwl
Mob. : 9301123085, Ph. : 4062091
Compiled By: Sandeep Sappal
Inline Function
✓ One of the objectives of using functions in a program is to save some memory space,
which becomes appreciable when a function is likely to be called many times.
However, every time a function is called, it takes a lot of extra time in executing a
series of instructions for tasks such as jumping to the function, saving registers, pushing
arguments into the stack, and returning to the calling function. When a function is small,
a substantial percentage of execution time may be spent in such overheads.
✓ To eliminate the cost of calls to small function, C+ + propose a new feature called inline
function. An inline function is a function that is expanded in line when it is invoked. That
is, the compiler replaces the function call with the corresponding function code . The
inline function are defined as follows:
Inline function-header
function
Example
{
return (a*a*a);
}
Some of the situations where inline expansion may not work are:
Note: Inline expansion makes a program run faster because the overhead of a function Call
and return is eliminated. However, it makes the program to take up more memory because
the statements that define the inline function are reproduced at each point where the
14
13,Gulabchand ki Bagichi, Behind Jhawer Estate, Thatipur Gwl
Mob. : 9301123085, Ph. : 4062091
Compiled By: Sandeep Sappal
function is called.
Default Argument.
✓ C+ + allows us to call a function without specifying all its arguments . In such cases,
the function assigns a default value to the parameter which does not have a matching
argument in the function call.
✓ Default values are specified when the function is declared. The compiler looks at the
prototype to see how many arguments a function uses and alerts the program for
possible default values.
The above prototype declares a default value of 0.15 to the argument rate,
A default argument is checked for type at the time of declaration and evaluated at the time of
call. One important point to note is that only the trailing arguments can have default values. It
is important to note that we must add defaults from right to left. We cannot provide a default
value to a particular argument in the middle of an argument list .some examples of function
declaration with default values:
✓ Default arguments are useful in situations where some arguments always have the
same value. For instance, bank interest may remain the same for all customers for a
particular period of deposit.
Function OverLoading:
✓ As stated earlier, overloading refers to the use of same thing for different purpose.
C++ Also permits overloading of functions. This means that we can use the same
function name to create functions that perform a variety of different tasks. This is
known as function polymorphism in OOP.
✓ Using the concept of function overloading; we can design a family of functions with
one function name but with different argument lists, The function would perform
different operations depending on the argument list in the function call.
✓ The correct function to be invoked is determined by checking the number and type of
the arguments but not on the function type. For example, an overloaded add ()
function handles different types of data as shown below:
// Declarations
// function calls
A function call first matches the prototype having the same number and type of arguments
and then calls the appropriate function for execution. A best match be unique.
✓ The compiler first tries to find an exact match in which the types of actual arguments
are the same, and use that function.
✓ If an exact match is not found, the compiler uses the integral promotions to the actual
arguments, such as,
o Char to int
o Float to double
To find a match.
✓ When either of them fails, the compiler tries to use the built-in conversions (the
implicit assignment conversions ) to the actual arguments and then uses the function
whose match is unique.
✓ If all of the step fail, then the compiler will try the user-defined conversions in
combination with integral promotions and built-in conversions to find a unique match.
User-defined conversions are often used in handling class objects.
Constructor
✓ It is called constructor because it constructs the values of data members of the class.
class integer
int m, n;
public:
…..
};
{ m= 0; n = 0;
when a class contains a constructor like the one defined above, it is guaranteed that an
object created by the class will be initialized automatically. For example, the declaration
not only creates the object intl of type integer but also initializes its data members m and n
to zero. There is no need to write any statement to invoke the constructor function (as we do
with the normal member function ) If a `normal ` member function is defined for zero
initialization, we would need to invoke this function for each of the objects separately , this
would be very inconvenient, if there are a number of objects .
A constructor that accepts no parameters is called the default constructor. The default
constructor for class A is A::A() .if no such constructor is defined, then the compiles supplies a
default constructor.
• They do not have return types, not even void and therefore, and they cannot return
values.
• They cannot be inherited, though a derived class can call the base class constructor.
• They make `implicit calls` to the operators new and delete when memory allocation is
required.
Copy Constructor
As stated earlier, a copy constructor is used to declare and initialize an object from another
object. For example, the statement
18
13,Gulabchand ki Bagichi, Behind Jhawer Estate, Thatipur Gwl
Mob. : 9301123085, Ph. : 4062091
Compiled By: Sandeep Sappal
Integer A (B);
Would define the object A and at the same time initialize it to the values of B. Another form
of this statement is
Integer A = B
A = B;
will not invoke the copy constructor . However, if A and B are objects, this statement is legal
and simply assigns the values of B to A.
✓ When no copy constructor is defined, the compiler suppliers its own copy constructor .
Destructor.
A destructor is used to destroy the objects that have been created by a constructor . like a
constructor , the destructor is a member function whose name is the same as the class
name but is preceded by a tilde . for example, the class integer can be defined as shown
below:
~ integer () { }
Properties of Destructors
✓ A destructor never takes any argument nor does it return any value.
✓ It will be invoked implicitly by the compiler upon exit from the program (or block or
function as the case may be ) to clean up storage that is no longer accessible.
19
13,Gulabchand ki Bagichi, Behind Jhawer Estate, Thatipur Gwl
Mob. : 9301123085, Ph. : 4062091
Compiled By: Sandeep Sappal
✓ Whenever new is used to allocate memory in the constructors, we should use delete
to free that memory . for example, the destructor for the matrix class discussed
above may be defined as follows:
Matrix :: ~matrix ()
delete p[i];
delete p;
this is required because when the pointers to objects go out of scope, a destructor is not
called implicitly.
Operator Overloading
✓ The Operator overloading is one of the many exciting features of C++ language . It is
important technique that has enhanced the power of extensibility of C++
✓ This means that C++ has the ability to provide the operators with a special meaning
for a data type. The mechanism of giving such special meanings to an operator is
known as operator overloading.
✓ Operator overloading provides a flexible option for the creation of new definitions for
most of the C++ operators. We can almost create a new language of our own by the
creative use of the function and operator overloading techniques. We can overload
(give additional meaning to ) all the C++ Operator Except the following:
To define an additional task to an operator, we must specify what it means in relation to the
class to which the operator is applied. This is done with the help of operator function, called
operator function, which describes the task. The general form of an operator function is :
where< return type >is the type of value returned by the specified operation and <op> is
the operator being overloaded. the<op> is preceded by the keyword operator . operator
op is the function name .
Operator functions must be either member functions (non-static ) or friend functions. A basic
difference between them is that a friend function will only one argument for unary operators
and two for binary operators, while a member function has no argument for unary operators
and only one for binary operators. This is because the object used to invoke the member
function is passed implicitly and therefore is available for the member function. This is not the
case with friend functions.
21
13,Gulabchand ki Bagichi, Behind Jhawer Estate, Thatipur Gwl
Mob. : 9301123085, Ph. : 4062091
Compiled By: Sandeep Sappal
Reusability is yet another important feature of OOP. It is always nice if we could reuse
something that already exists rather than trying to cerate the same all over again. It would not
only save time and money but also reduce frustration and increase reliability. For instance, the
reuse of a class that has already been tested, debugged and many times can save us the effort
of developing and testing the same again.
Fortunately, C++ strongly supports the concept of reusability. The C++ classes can be reused in
several ways. Once a class has been written and tested, it can adapted by other programmers
to suit their requirements. This is basically done by creating new classes, reusing the
properties of the existing ones the mechanism of deriving a new class from an old one is called
inheritance (or derivation). The old class is referred to as the base class and the new one is
called the derived class or subclass.
The derived class inherits some or all of the traits form the base. A class can also inherit
properties from more than one class or from than one level. A derived class with only one base
class, is called single inheritance and one with several base classes is called multiple inheritance
. on the other hand, the traits of one class may be inherited by more than one class. This
process is known as hierarchical inheritance. The mechanism of deriving a class from another
derived class is known as multilevel inheritance.
…….//
…….//
};
The colon indicates that the derived-class-name is derived from the base-class-name. The
visibility-mode is optional and, if present, may be either private or public. The default visibility –
mode is private. Visibility mode specifies whether the features of the base class are privately
derived or publicly derived.
When a base class is privately inherited by a derived class, `public members` of the base
22
13,Gulabchand ki Bagichi, Behind Jhawer Estate, Thatipur Gwl
Mob. : 9301123085, Ph. : 4062091
Compiled By: Sandeep Sappal
class become `private members` of the derived class and therefore the public members of the
base class can only be accessed by the member functions of the derived class they are
inaccessible to the objects of the derived class. Remember, a public member of a class can be
accessed by its own objects using the dot operator . The result is that no member of the base
class is accessible to the objects of the derived class .
On the other hand, when the base class is publicly inherited, `public members` of the base class
become `public members` of the derived class and therefore they are accessible to the objects
of the derived class. In both the cases, the private members are not inherited and therefore, the
private members of a base class will never become the members of its derived class.
Types of Inheritance:
23
13,Gulabchand ki Bagichi, Behind Jhawer Estate, Thatipur Gwl
Mob. : 9301123085, Ph. : 4062091
Compiled By: Sandeep Sappal
A
A B
B C D
C
A A
B C
B
D
C
Protected Members
We have just seen how to increase the capabilities of an existing class without modifying it. We
have also seen that a private member of a base class cannot be inherited and therefore it is not
available for the derived class directly. What do we do if the private data needs to be inherited
by a derived class? This can be accomplished by modifying the visibility limit of the private
member by making it public. This would make it accessible to all the other functions of the
program, thus taking away the advantage of data hiding.
24
13,Gulabchand ki Bagichi, Behind Jhawer Estate, Thatipur Gwl
Mob. : 9301123085, Ph. : 4062091
Compiled By: Sandeep Sappal
C++ provides a third visibility modifier, protected, which serve a limited purpose in inheritance.
A member declared as protected is accessibly by the member functions within its class and any
class immediately derived from it. It cannot be accessed by the functions outside these two
classes. A class can now use all the three visibility modes as illustrated below:
Class alpha
private : // optional
protected:
public:
…… // in the program
When a protected member is inherited in public mode , it becomes protected in the derived
class too and therefore is accessible by the member functions of the derived class. It is also
ready for further inheritance. A protected member, inherited in the private mode derivation,
becomes private the derived class. Although it is available to the member functions of the
derived class, it is not available for further inheritance (since private members cannot be
inherited ).
Consider a situation where all the three kinds of inheritance, namely, multilevel, multiple and
25
13,Gulabchand ki Bagichi, Behind Jhawer Estate, Thatipur Gwl
Mob. : 9301123085, Ph. : 4062091
Compiled By: Sandeep Sappal
hierarchical inheritance, are involved. This is illustrated in the figure that `child` has two direct
base classes `parent1` and `parent2` which themselves have a common base class
`grandparent`. The `child` inherits the traits of `grand parent` via two separate paths. It can
also inherit directly as shown by the broken line. The `grandparent` is sometimes referred to as
indirect base class.
Grandparent
Parent 1 Parent 2
Child
Multipath inheritance
Inheritance by the `child` as shown in might pose some problems. All the public and protected
members of `grandparent` are inherited into `child` twice, first via `parent1` and again via
`parent2` this means, `child` would have duplicate sets of the members inherited from
`grandparent`. This introduces ambiguity and should be avoided.
The duplication of inherited members due to these multiple paths can be avoided by making
the common base class (ancestor class)as virtual base class while declaring the direct or
intermediate base classes which is shown as follow:
Class A // grandparent
……
26
13,Gulabchand ki Bagichi, Behind Jhawer Estate, Thatipur Gwl
Mob. : 9301123085, Ph. : 4062091
Compiled By: Sandeep Sappal
……
};
……
……
};
……
};
…… // will be inherited
};
When a class is made a virtual base class, C++ takes necessary care to see that only one copy of
that class is inherited, regardless of how many inheritance paths exist between the virtual base
class and a derived class.
Note: The keywords virtual and public may be used in either order.
27
13,Gulabchand ki Bagichi, Behind Jhawer Estate, Thatipur Gwl
Mob. : 9301123085, Ph. : 4062091
Compiled By: Sandeep Sappal
Polymorphism
Polymorphism
Compile time
Polymorphism Run time
Polymorphis
m
Achieving polymorphism
Polymorphism is one of the crucial features of OOP. It simply means `one name , multiple forms.
We have already seen how the concept of polymorphism is implemented using the overloaded
functions and operators. the overloaded member functions are `selected` for invoking by
matching arguments, both type and number. This known to the compiler at the compile time
and, therefore, compiler is able to select the appropriate function for a particular call at the
compile time itself. This is called early binding or static binding or static linking . Also known as
compile time polymorphism, early binding simply means that an object is bound to its function
call compile time.
28
13,Gulabchand ki Bagichi, Behind Jhawer Estate, Thatipur Gwl
Mob. : 9301123085, Ph. : 4062091
Compiled By: Sandeep Sappal
At run time, when it is known what class objects are under consideration, the appropriate
version of the function is invoked. Since the function is linked with a particular class much later
after the compilation, this process is termed as late binding. It is also known as dynamic binding.
When we use the same function name in both the base and derived classes, the function in
base class is declared as virtual the using the keyword virtual preceding its normal
declaration . when a function is made virtual, C++ determines which function to use at run
time based on the type of object pointed to by the base pointer, rather than the type of
pointer. Thus, by making the base pointer to point to different object, we can execute
different versions of the virtual function.
When virtual functions are created for implementing late binding., we should observe some
basic rules that satisfy the complier requirements :
5. A virtual function in a base class must be defined, even though it may not be used.
6. The prototypes of the base class version of a virtual function and all the derived class
versions must be identical. If tow functions with the same name have different
prototypes, C++ considers them as overloaded functions, and the virtual function
mechanism is ignored .
29
13,Gulabchand ki Bagichi, Behind Jhawer Estate, Thatipur Gwl
Mob. : 9301123085, Ph. : 4062091
Compiled By: Sandeep Sappal
8. While a base pointer can point to any type of the derived object, the reverse is not true.
That is to say , we cannot use a pointer to a derived class to access an object of the base
type.
9. If a virtual function is defined in the base class, it need not be necessarily redefined in
the derived class. In such cases, calls will invoke the base function.
the derived classes. The function inside the base class is seldom used for performing any task.
It only serves as a placeholder. For example, we have not defined any object of class media and
therefore the function display () in the base class has defined `empty` such functions are called
“do-nothing” functions.
Such functions are called pure virtual functions. pure virtual function is a function declared in
base class that has no definition relative to the base class. In such cases, the complier requires
each derived class to either define the function or redeclare it as pure virtual function.
Remember that class containing pure virtual functions cannot be used to declare any objects of
its own .As stated earlier, such classes are called abstract base classes and to create a base
pointer required for achieving run time polymorphism.
this Pointer
The this pointer is used as a pointer to the class object instance by the member function. The address of the class
instance is passed as an implicit parameter to the member functions. C++ keeps only one copy of each member
function and the data members are allocated memory for all of their instances. This kind of various instances of
data are maintained use this pointer.
• this pointer stores the address of the class instance, to enable pointer access of the members to the
member functions of the class.
• this pointer is not counted for calculating the size of the object.
• this pointers are not accessible for static member functions.
• this pointers are not modifiable.
30
13,Gulabchand ki Bagichi, Behind Jhawer Estate, Thatipur Gwl
Mob. : 9301123085, Ph. : 4062091
Compiled By: Sandeep Sappal
OOPS PART-3
Abstraction
✓ Abstract classes
A class that contains one or more abstract methods and therefore can never be instantiated.
Abstract class are defined to the other classes can extend them and make them concrete by
implementing the abstract methods. An abstract class has no direct instances but whose
descendent classes have direct instances. Its objects cannot be created and the subclass of
abstract class may have instance(object). The function defined in abstract class does not have
any body. It is used as a foundation for derived classes.
Abstract classes are defined just as ordinary classes. However, some of their methods are
designated to be necessarily defined by subclasses. We just mention their signature including
their return type, name and parameters but not a definition. One could say, we omit the
method body or, in other words, specify “nothing ‘’.this is expressed by appending “=0” after
the method signatures.
An abstract class contains at least one pure virtual function. Object of abstract class cannot be
created.
Example:
class Media
{
public:
virtual void Show ()=0;
};
void main ()
{ Media *A
A= new A; //cannot create object of an abstract class
A->Show();}
This class definition would force every derived class from which objects should be created to
define a method Show (). These method declarations are also called pure methods.
Abstract classes are set up for the benefit of derived classes. Abstract normally occur at the root
of the hierarchy .there can be any number of abstract classes in the same hierarchy.
class A
virtual void Function ()=0;
class B
virtual void Function ();
class C
virtual void Function();
An abstract class with one or more pure virtual31functions has the following properties:
13,Gulabchand ki Bagichi, Behind Jhawer Estate, Thatipur Gwl
Mob. : 9301123085, Ph. : 4062091
Compiled By: Sandeep Sappal
✓ Abstract Method:
When derive class has same signature of method as in base class then a complexity occurred
called Method overriding. Method Overriding is basically implemented in inheritance to extend
the functionality of Member Function. The main task of Method Overriding is to apply run time
polymorphism (RTP).
To Apply RTP, We have to define abstract method(do nothing method) within the base class.
Abstract Method have following properties.
The wrapping up of data and function within a single unit(class) is known as encapsulation.
Encapsulation is the way to implement the data abstraction.
Data encapsulation is the most striking feature if the class. The data is not accessible to the
outside world, only those function which wrapped in the class can access it. These function are
interface between object data and the program. This insulation of the data from the direct
access by the program is called Data Hiding.
Abstraction refers to the act of representing essential features without including the
background details of explanations. Classes uses the concept of data hiding means the member
which declare in private section of class can’t access by any external function.
This feature is also kwon as ADT(abstract data type).
Ex. To understand the abstraction lets take an example of car, you anly know the essential
feature of car like gear handling , steering handling, use of break and clutch etc.
But while driving a car you don’t know about the engine, gear, break, clutch, how it is Internally
working.
PASCAL, the compiler call fixed function identifiers, based on the source code. In early binding,
the function identifiers are associated with physical addresses before runtime and during the
process of compilation and linkage. The compiler calls fixed function identifiers, based on
source code. The linker takes these identifiers and replaces them with a physical address.
Examples:
1. Standard function calls.
2. Overloaded function and operator calls.
Advantage: it is faster and often requires less memory.
Disadvantage: lack of flexibility.
Late binding: A function call is only indicated in the source code, without specifying the exact
function to call is known as late binding. In nutshell, function calls are resolved at run time.
Advantages:
1. Allows greater flexibility.
2. Used to support a common interface, while allowing various objects utilizing this
interface to define their own implementations.
3. Used to create class libraries that can be reused and extended. Disadvantages: little loss
of execution speed.
See Virtual Function
✓ Association
Association describes a group of links with common structure and common semantics. All links
in an association connect objects from the same class .it describes a set of potential links.
Associations are bi-directional. The implementation of associations through programming
languages is as pointer from one object to another. Pointer is an attribute of an object that
contains an explicit reference to another object.
Associations are important because they define the routes for message passing between
objects.
Importance of associations
1. Association has been widely used throughout the database modeling.
2. Most object-oriented language implement associations with object pointers.
3. Associations violate encapsulation of information into classes.
Associations are a link between objects of two or more classes. An association exists between
objects of different classes whenever there is a logical linking, interaction, or dependency
between the objects. An association relationship may be described as “has a”, “associated with”
or “knows about”.
An association has a cardinality or multiplicity. This is the number of objects on one side of an
association that may be associated with an object on the other side of the association. For
example, one car has one passenger. This is an example of a l to l association. If a car object may
have many passenger objects, then there is a l to many association between the car class and
the passenger class.
The association relationship is important for many reasons. Association is the most fundamental
relationship of real world physical things and software entities. Association
helps develop highly cohesive objects where 33all associated objects are linked to
13,Gulabchand ki Bagichi, Behind Jhawer Estate, Thatipur Gwl
Mob. : 9301123085, Ph. : 4062091
Compiled By: Sandeep Sappal
1:*
Canvas ID Drawing
Usually a name identifies an Object within some context, this name uniquely identify
an object. Drawing class has Object (ID) or qualifier like Circle, Square, and Cube etc.
A Qualifier
Distinguishes objects on the “many” side of an association.
Identify association by looking for logical links or connections between two or more objects. One object
may “know about” another object. For example, a retail store “knows about” its employees. One object
may “depend upon “another object. For example, a bank “depends upon” its tellers. Often it is useful to
make a drawing of the key objects in a system and show the association between the objects on the
drawing. For each object on the drawing, identify associations between them.
Recursive Association:
A recursive association is where a class is associated to itself. In the recursive association only one class is
involved this is the type of association used with linked lists.
Example of Recursive Association
The relationship of supervisor nurse supervises nurse(member) can be expressed in two different model.
34
13,Gulabchand ki Bagichi, Behind Jhawer Estate, Thatipur Gwl
Mob. : 9301123085, Ph. : 4062091
Compiled By: Sandeep Sappal
Model A:
Supervises
Supervisor Nurse Member Nurse
Model B:
Nurse
Supervise
Consider: is there any different behavior between supervisor nurse and member nurse? If no, then all we
need to do is to show the relationship between them and a single class with a recursive association
(model B) is sufficient. However, if the answer is yes, then we need two separate classes (model A) to
handle the different requirements (like the example of Supervisor Nurse Supervise Member Nurse –two
classes are needed to set the Relationship).
The above model shows the one to one association between objects that a one car is used by one person
Has Designation
(Employee) (Designation)
Deepak Manager
Instance
(Employee) (Designation)
Has Designation Diagram
Vijay Clerk
Each association in the class diagram corresponds to a set of links in the instance diagram, just as each
class corresponds to a set of objects. Each employee has Designation. Designation is the name of the
association.
Many to many association
Many associations are traversed in both directions, although not usually with equal frequency,
his approach permits fast access, but if either attribute is updated then the other attribute
must also be updated to keep the link35consistent there are many approaches to their
13,Gulabchand ki Bagichi, Behind Jhawer Estate, Thatipur Gwl
Mob. : 9301123085, Ph. : 4062091
Compiled By: Sandeep Sappal
implementation:
1:*
Car Person
The above model shows the one to many association between objects that a one car is used by many
person.
Ternary Association: The Diamond Shape symbol is used to define Ternary Association between objects.
Projects Language
Class
Diagram
Programmer
(Project) (Language)
Accounts Cobol
Instance
Programmer Diagram
(Project) (Language)
CAD C
In above model a programmer know more then one language and design more then one project in
various language. The diamond shape operator here shows association of programmer with both project
and language.
✓ Aggregation
Objects which are composed of other objects are known as aggregations. They may involve
containment (the contained objects are components of the larger object) or containership .
Overview
Containment v Containers
A commonly used term for this type of class relationship is containment’ but there is a semantic
difference between this term and the idea of container classes’ which also may contain objects
of other classes, but do not depend on them for their representation. There fore, although they
can both be seen as types of aggregation, we should draw an important distinction between
containment and containers, as follows: 36
13,Gulabchand ki Bagichi, Behind Jhawer Estate, Thatipur Gwl
Mob. : 9301123085, Ph. : 4062091
Compiled By: Sandeep Sappal
A Car Engine, gear, clutch etc. is the fixed component of car, without these components a
car is not complete car so this type of component relationship is fixed in nature and called
Containment Relationship.
On other Hand if a car contain luggage then this relationship is called variable relationship
because without luggage a car is a complete car thus this represent
Container Relationship.
Luggage
Engine Luggage
Layers of aggregation
Aggregation may well exist several layers so that objects are composed off component objects
which themselves are composed of other objects. A train, for example, is composed of one or
more locomotives and a number of coaches or wagons. The locomotives and coaches/wagons
are composed of many smaller components.
The objects which comprise parts of a larger object may not have an exis-tence independent of
the larger object.
Aggregation can be fixed, variable or recursive:
1. Fixed the particular number and types of the component parts are predefined eg a
car has one engine, four wheels, one steering wheel etc.
2. Variable : the number of levels of aggregation are fixed, but the number of parts
may vary (like the train )
3. Recursive: the object contains components of its own type, a Russian doll (each one
containing a smaller doll) A more specific example in C++ is the ability for an object
to contain a pointer of its own type allowing it to send messages to other objects of
the same class.
✓ Benefits of Oops
• Through inheritance, we can eliminate redundant code and extend the use of existing
• We can build programs from the standard working modules that communicate with one
another, rather than having to start writing the code from scratch. This leads to saving
of development time and higher productivity.
• The principle of data hiding helps the programmer to build secure programs that cannot
be invaded by code in other parts of the program.
• It is possible to have multiple instances of object to co-exits without any interference.
• It is possible to map objects in the problem domain to those in the program.
• It is easy to partition the work in a project based on objects.
• The data-centered design approach enables us to capture more details of a model in
implement able form.
• Object-oriented systems can be easily upgraded from small to large systems .
• Message passing techniques for communication between objects makes the interface
description with external systems much simpler.
• Software complexity can easily manage.
✓ Disadvantage of Oops
(i) Resource demands – since an object oriented program can require a much greater
processing overhead than one written using traditional methods, it work more
slowly this not a good from a customer’s point of view.
(ii) Object persistence –an object natural environment is in RAM as a dynamic entity.
This is in contrast to traditional data storage in files or databases where the natural
environment of the data is on external storage. This causes
problem when we want objects to 38 persist between runs of a program,
13,Gulabchand ki Bagichi, Behind Jhawer Estate, Thatipur Gwl
Mob. : 9301123085, Ph. : 4062091
Compiled By: Sandeep Sappal
✓ Types of object
There are four types of object (or in fact any other data type) which we may instantiate in
program.
39
13,Gulabchand ki Bagichi, Behind Jhawer Estate, Thatipur Gwl
Mob. : 9301123085, Ph. : 4062091
Compiled By: Sandeep Sappal
Automatic objects
As well as external global objects we may also have a number of locally declared Automatic
objects –objects which exist in a predictable manner for a particular period of time. The key
difference between an external and automatic object is that whereas an automatic objects
instantiated within the scope of part of a program module, an external object is in instantiated
outside of any scope (in C++ scope is defined by braces ) `automatic` objects are automatically
destroyed when they fallout of the scope in which they were instantiated .
Static objects
External objects are persistent and visible throughout the lifetime of a program, whereas
automatic objects are only persistent and visible within the scope in which they are declared.
There is also the possibility in C++ to explicitly declare a variable or object which has the scope
(in terms of visibility) of an automatic objects but the lifetime of an external object. This is
known as a ‘static object’
Difference
External objects exist for the lifetime of the program and their visibility is global. Automatic
objects exist as long as they remain in scope and are visible only within that scope. Static
objects are created and visible within a particular scope, but persist from their point of creation
until the end of the program.
Dynamic Objects
When we cannot predict the identities, and lifetime of the objects which will be represented at
run time, then they cannot be uniquely named is (i.e. they cannot be external, static or
automatic.) if objects are unpredictable, then they must be represented dynamically.
1. Creating and destroying dynamic objects using the `new` and delete` operators,
2. Calling the methods of dynamic objects using the `arrow` operator (->)
E->getValues();
3. Destroying Objects
delete E;
We know that it is very rare that a program works correctly first time. It might have bugs. The
two most common types of bugs are logic errors and syntax errors. The logic errors occur due to
poor understanding of the problem and solution procedure. The syntactic errors arise due to
poor understanding of the language itself. We can detect these errors by using exhaustive
debugging and testing procedures.
We often come across some peculiar problems other than logic or syntax errors. They are
known as exceptions. Exceptions are run time error or unusual conditions that a program may
encounter while executing. Run time Error might include conditions such as division by zero,
access to an array outside of its bounds, or running out of memory or disk space. When a
program encounters as exceptional condition, it is important that identified and dealt with
effectively run time errors.
Exception handing was not part of the original C++ it is new feature added to ANSI C++.
41
13,Gulabchand ki Bagichi, Behind Jhawer Estate, Thatipur Gwl
Mob. : 9301123085, Ph. : 4062091
Compiled By: Sandeep Sappal
Exceptions are of two kinds, namely, synchronous exceptions and asynchronous. Errors such as
“out-of-range index” and “over-flow” belong to the synchronous type exceptions. The errors
that are caused by events beyond the control of the program (such as keyboard interrupts) are
called asynchronous exceptions. The proposed exception handling mechanism in C++ is
designed to handle only synchronous exceptions.
The mechanism suggests the following tasks:
1. Find the problem (hit the exception).
2. Inform that as errors has occurred (throw the exception).
3. Receive the errors information (catch the exception).
4. Take corrective actions (handle the exception).
The errors handling code basically consists of two segments, one to detect errors and to throw
exceptions, and the other to catch the exceptions and to the take appropriate actions.
C++ exceptions handling mechanism is basically built upon three keywords, namely, try,
throw, and catch the keyword try is used to preface a block of
Try block
using a throw statement in the try block. A catch block defined by the keyword catch ‘catches’
the exception ‘thrown’ by the try block, and handles it appropriately. The relationship is shown
in fig:
Exception
object Catch block
catches and handles
the exception
The catch block that catches as exception must immediately follow the try block that throws the
exception, the general form of these two block are as follows.
…..
….. try
{
…..
throw exception // block of statements which
….. // detect and throws an exception
…..
42
13,Gulabchand ki Bagichi, Behind Jhawer Estate, Thatipur Gwl
Mob. : 9301123085, Ph. : 4062091
Compiled By: Sandeep Sappal
}
catch (type arg) // catches exception
{
…..
….. // block of statements that
….. // handles the exception
…..
}
.....
….
When the try block throws an exception, the program control leaves the try block and enters
the catch statement of the catch block where user can customize the error message.
✓ Benefits of inheritance
Inheritance offers many useful features to programmers, Classes are easily maintainable and
understandable when set relationship between class using inheritance.
To construct the object model we must identify the relevant object and classes from the
application domain. Object includes physical entities like houses, employee and machine.
While identifying class we must emphasis on logical relationship, association and aggregations.
Analysis of relationships between the classes is central to the structure of a system. Therefore,
it is important to identify appropriate classes to represent the object in the solution space and
establish their relationships. The major relationships that are important in the context of design
are:
1) Inheritance Relationships
2) Containment Relationship
3) Use Relationship(Aggregation)
Identifying Objects 43
13,Gulabchand ki Bagichi, Behind Jhawer Estate, Thatipur Gwl
Mob. : 9301123085, Ph. : 4062091
Compiled By: Sandeep Sappal
There are three helpful ways you identify objects when you are designing the system.
1) A Checklist kind of objects
a) External entities
b) Things
c) Occurrences of Events
d) Roles
e) Organizational units
f) Places
g) Structures
2) Grammatical parse of a piece of text describing the problem and outline Solution
In the grammatical parse you select the nouns and noun Phrases as the potential
objects and verbs as possible operation performed or by the objects.
Like Bank Customer1, Customer2;
Customer text represents Bank Customer.
3) Potential Objects
a) Retained Information- the objects needs to remember information.
b) Needed Service- the object has operations which changes its attributes.
c) Common Attributes- all occurrences of an object have the attributes.
d) Common Operation- all occurrences of an object have the operations.
e) Essential Requirements-External entities, which produce, consume Information.
f) Multiple Attributes- holds a state of object.
44
13,Gulabchand ki Bagichi, Behind Jhawer Estate, Thatipur Gwl
Mob. : 9301123085, Ph. : 4062091
Compiled By: Sandeep Sappal
Introduction
Template could be used as a standard approach for storing and processing of data. The
collection of these generic classes and function is called the Standard Template Library (STL).
The STL has now become a part of ANSI standard C++ class library.
COMPONENTS OF STL
The STL contains several components. But at its core are three key components. They are:
Containers,
Algorithms, and
iterators.
These three components work in conjunction with one another to provide support to a
variety of programming solution. The relationship between the three components is shown
in Fig Algorithms employ iterators to perform operation stored in containers.
Container
Iterator1
Algorithm iterator2
Algorithm
1 2
Object1
Object2
Iterator3
Object3
Sequence Containers
Sequence containers store elements in a linear sequence, like a line as shown in Fig. Each
element is related to other element by its position along the line. They all expand themselves
to allow insertion of elements and all of them support a number of operation on them.
•
Element0 Element1 Element2 Last
Element
iterator
begin end()
Elements in a sequence container
Associative Containers
Associative containers are designed to support direct access to elements using keys. they
are not sequential. There are four types of associative container:
Set
45
13,Gulabchand ki Bagichi, Behind Jhawer Estate, Thatipur Gwl
Mob. : 9301123085, Ph. : 4062091
Compiled By: Sandeep Sappal
Multiset
Map
Multimap
All these containers store data in a structure called tree which facilitates fast searching,
deletion, and insertion. However, these are very slow for random access and inefficient for
sorting.
Derived Containers
The STL provider three derived containers namely, stack, queue, and priority _queue These
are also known as container adaptors. Stacks, queues and priority queue can be created from
different sequence containers. The derived containers do not support iterators and therefore we
cannot use them for data manipulation. However, they support two member functions pop() and
push() for implementing deleting and inserting operations.
ALGORITHMS
Algorithms are functions that can be used generally across a variety of containers for processing
their contents. Although each container provides functions for its basic operations, STL provides
more than sixty standard algorithms to support more extended or complex operations. Standard
algorithm also permit us to work with two different type of containers at the same time.
Remember, STL algorithms are not member functions or friends of containers. They are
standalone template function.
STL algorithms, based on the nature of operations they perform, may be categorized as under.
• Retrieve or non – mutating algorithms
• Mutating algorithms
• Sorting algorithms
• Set algorithms
• Relational algorithms
46
13,Gulabchand ki Bagichi, Behind Jhawer Estate, Thatipur Gwl
Mob. : 9301123085, Ph. : 4062091
Compiled By: Sandeep Sappal
ITERATORS
Iterators behave like pointers and are used to access container elements. They are often used to
traverse from one element to another, a process known as iterating through the container.
There are five types of iterators as described in Table
The input and output iterators support the least functions. They can be used only to traverse in a
container. The forward itrerator support all operations of input and output itrerators and also
retains its position in the container. A bidirectional itreator, while supporting all forward itrerator
operations, provides the ability to move in the backward direction in the container. A random
access iterator combines the functionality of a bidirectional iterator with an ability to jump to an
arbitrary location. Table sum marizes the operation that can be performed on each iterator type.
Table Operations supported by iterators
Iterator Element access Read Write Increment operation comparison
Vectors
The vector is the most widely used container. It stores elements in contiguous memory locations
and enable direct access to any element using the subscript operator[]. A vector can change its
size dynamically and therefore allocates memory as needed at run time.
The vector container supports random access iterators, and a wide range of iterator operations
See may be applied to a vector iterator. Class vector supports a number of constructors for
creating vector objects.
48
13,Gulabchand ki Bagichi, Behind Jhawer Estate, Thatipur Gwl
Mob. : 9301123085, Ph. : 4062091
Compiled By: Sandeep Sappal
The metaclass
The use of ‘meta’ as a prefix has a wide range of meanings, including, simply, ‘about’, the term
‘metaclass’ is similer in usage to ‘metalanguage’- a language used to describe some other
language (ie the metalanguage tells us about the language).
There are also a number of terms where ‘meta’ is used to imply some form of abstraction (such
as ‘metaphysics’). From these interpretations we may conclude that the metaclass tells us about
the class. And may be seen as an abstraction of the class in the same way that the class (as an
‘abstract data type’) is an abstraction of a set of object. The metaclass is often described as the
‘class of a class’, the class, as we know, holds the attributes and methods which will apply to
objects of the class – it is the class of the objects.
The metaclass hold the attributes and methods which will apply to the class itself – therefore it is
the class of the class ! (see figure).
Every class has one (and only one) metaclass. And the meta class contain those parts of a class
which are not appropriate to be duplicated for every specific object.
The metaclass may seem a rather esoteric concept(mysterious), but it is basically a repository for
those part of a class which must exist at the run time of a program(objects).
OBJECT
Class
Metaclass
class object
attributes attributes OBJECT
and Class and attributes (static member) OBJECT
methods Consider a methods large system which keep track of bank system
where we maintain customer account as well as bank account in case of
customer account we must create diffrent object for each customer that contain accountID,
customer name and its balance.
Object attribute
Customer1
Class attribute ACN name balance
Bank Balance
Customer2
Customer3
What is UML?
UML stands for Unified Modeling Language. This object-oriented system of notation has
evolved from the work of Grady Booch, James Rumbaugh, Ivar Jacobson, and the Rational
Software Corporation. These renowned 50computer scientists fused their respective
13,Gulabchand ki Bagichi, Behind Jhawer Estate, Thatipur Gwl
Mob. : 9301123085, Ph. : 4062091
Compiled By: Sandeep Sappal
technologies into a single, standardized model. Today, UML is accepted by the Object
Management Group (OMG) as the standard for modeling object oriented programs.
Types of UML Diagrams
UML defines nine types of diagrams: class (package), object, use case, sequence, collaboration,
statechart, activity, component, and deployment.
Class Diagrams
Class diagrams are the backbone of almost every object oriented method, including UML. They
describe the static structure of a system.
Package Diagrams
Package diagrams are a subset of class diagrams, but developers sometimes treat them as a
separate technique. Package diagrams organize elements of a system into related groups to
minimize dependencies between packages.
Object Diagrams
Object diagrams describe the static structure of a system at a particular time. They can be used to
test class diagrams for accuracy.
51
13,Gulabchand ki Bagichi, Behind Jhawer Estate, Thatipur Gwl
Mob. : 9301123085, Ph. : 4062091
Compiled By: Sandeep Sappal
Sequence Diagrams
Sequence diagrams describe interactions among classes in terms of an exchange of messages
over time.
Collaboration Diagrams
Collaboration diagrams represent interactions between objects as a series of sequenced messages.
Collaboration diagrams describe both the static structure and the dynamic behavior of a system.
Statechart Diagrams
Statechart diagrams describe the dynamic behavior of a system in response to external stimuli.
Statechart diagrams are especially useful in modeling reactive objects whose states are triggered
by specific events.
Activity Diagrams
Activity diagrams illustrate the dynamic nature of a system by modeling the flow of control from
activity to activity. An activity represents an operation on some class in the system that results in
a change in the state of the system. Typically, activity diagrams are used to model workflow or
business processes and internal operation. 52
13,Gulabchand ki Bagichi, Behind Jhawer Estate, Thatipur Gwl
Mob. : 9301123085, Ph. : 4062091
Compiled By: Sandeep Sappal
Component Diagrams
Component diagrams describe the organization of physical software components, including
source code, run-time (binary) code, and executables.
Deployment Diagrams
Deployment diagrams depict the physical resources in a system, including nodes, components,
and connections.
53
13,Gulabchand ki Bagichi, Behind Jhawer Estate, Thatipur Gwl
Mob. : 9301123085, Ph. : 4062091
Compiled By: Sandeep Sappal
Object-oriented analysis (OOA) refers to the methods of specifying requirements of the software
in terms of real-world objects, their behavior, and their interaction . Object-oriented (OOD), on
the other hand turns the software requirements into specification for objects and derives class
hierarchies from which the objects can be created. Finally, Object oriented programming (OOP)
refers to the implementation of the program using objects, in an object-oriented programming
language such
as C++.
OBJECT-ORIENTED ANALYSIS
Object-oriented analysis provides us with a simple ,yet powerful, mechanism for identifying
objects, the building block of the software to be developed. The analysis is basically concerned
with the decomposition of a problem into its component parts and establishing a logical model to
describe the system function .
The object-oriented analysis (OOA) approach consists of the following steps:
Problem definition
Requirement
specification
54
13,Gulabchand ki Bagichi, Behind Jhawer Estate, Thatipur Gwl
Identify objects
Mob. : 9301123085, Ph. : 4062091
Problem Understanding
The first step in the analysis process is to understated the problem of the use. The problem
statement should be refined and redefined in terms of computer system engineering that could
suggest a computer-based solution. The problem statement should be stated, as far as possible, in
a single, grammatically correct sentence. This will enable the software engineers to have a highly
focused attention on the solution of the problem statement provides the basis for drawing the
requirements specification of both the user and the software .
Requirements Specification
Once the problem is clearly defined, the next step is to understand what the proposed system is
required to do. It is important at this stage to generate a list of user requirements. A clear
understanding should exist between the user and the developer of what is required .based on the
user requirements, the specifications for the software should be drawn. The developer should
state clearly:
• What outputs are required.
• What processes are involved to produce these outputs.
• What resources are required .
These specifications often serve as a reference to test the final product for its performance of the
intended tasks.
Identification of objects
Objects can often be identified in terms of the real-world objects as well as the abstract objects.
Therefore, the best places to look for objects is the application itself. The application may be
analyzed by using one of the following two approaches:
1. Data flow diagrams (DFD)
2. Textual analysis (TA)
Data flow diagram
The application can be represented in the form of a data flow diagram indicating how the data
moves from one point to another in the system. The boxes and data stores in the data flow
diagram are good candidates for the objects. The process bubbles correspond to the procedures.
Illustrates a typical data flow diagram. It is also known as a data flow graph or a bubble chart .
Data Books database
store
Shipping
instructions
Order
Bookseller Process Stores
order
Check credit
status
Shipment
Shipping information
Textual analysis notice
This approach is based on the textual Collect
description of the problem or proposed solution. The
customer
description may be of one or two sentences
order or one or two paragraphs depending on the type and
complexity of the problem. The nouns are good indicators of the objects. The names can further
be classified as proper nouns, common nouns, and mass or abstract nouns. Table shows the
various types of nouns and their meaning.
Type of noun OrderMeaning Instructions Example
Process
Customer order 55 Warehouse
it is important to identify appropriate classes to represent the objects in the solution space and
establish their relationships. The major relationships that are important in the context of design
are:
1. Inheritance relationships.
2. Containment relationships.
3. Use relationships.
Inheritance relationship is the highest relationship that can be represented in C++. It is a
powerful way of representing a hierarchical relationship directly. The real appeal and power of
the inheritance mechanism is that it allows us to reuse a class that is almost, but not exactly, what
we want and to tailor the class in a way that it does not introduce any unwanted side effects into
the rest of the class. We must review the attributes and operations of the classes and prepare an
inheritance relationship table as shown in Table
Class Depends on
A ….
B A
C A
D B
B1 B
B2 B
Containment relationship means the use of an object of a class as a member of another class.
This is an alternative and complimentary technique to use the class inheritance. But, it is often a
tricky issue to choose between the two techniques. Normally, if there is a need to override
attributes or functions, then the inheritance is the best choice, On the other hand, if we want to
represent a property by a variety of types, then the containment relationship is the right method to
follow. Another place where we need to use an object as a member is when we need to pass an
attribute of a class as an argument to the constructor of another class. The “another” class must
have a member object that represents the argument. The inheritance represents is_a relationship
and the containment represents has_a relationship.
Use relationship gives information such as the various classes a class uses and the way it uses
them. For example, a class A can use classes B and C in several ways:
• A reads a member of B.
• A call a member of C.
• A creates B using new operator.
Organization of Class Hierarchies
In the previous step, we examined the inheritance relationships. We must re-examine them and
create a class hierarchy so that we can reuse as much data and/or functions that have been
designed already. Organization of the class hierarchies involves identification of common
attributes and functions among a group of related classes and then combining them to form a new
class. The new class will serve as the super class and the others as subordinate classes (which
derive attributes from the super class). The new class may or may not have the meaning of an
object by itself. If the object is created purely to combine the common attributes, it is called an
abstract class.
Design of Classes
We have identified classes, their attributes, and minimal set of operations required by the concept
a class is representing. Now we must look at the complete details that each class represents. The
important issue is to decide what functions are to be provided. For a class to be useful, it must
contain the following functions, in addition to the service functions;
1. Class management functions.
57
13,Gulabchand ki Bagichi, Behind Jhawer Estate, Thatipur Gwl
Mob. : 9301123085, Ph. : 4062091
Compiled By: Sandeep Sappal
C++ Templates
C++ templates are a powerful mechanism for code reuse, as they enable the programmer to write code that behaves
the same for data of any type.
Templates in C++ programming allows function or class to work on more than one data type at once without
writing different codes for different data types. Templates are often used in larger programs for the purpose of
code reusability and flexibility of program.
Templates are also known as generic functions or classes which are used to implement a generic structure for many
structures of the same statements with different data-types.
Templates are expanded by the compiler in as many definitions as the function calls of the different types used.
We can declare a template with the keyword template. Like so:
template<typename T>
template<class T>
The template keyword tells the compiler that what follows is a template, and that T is a template parameter that
identifies a type.
There are two types of templates:
• Function templates
• Class templates
Function templates
#include <iostream.h>
template <class T>
T square(T x)
{ T result;
result = x * x;
return result;
}
void main()
{ int i=2, ii;
float x=2.2, xx;
double y=2.2, yy;
58
13,Gulabchand ki Bagichi, Behind Jhawer Estate, Thatipur Gwl
Mob. : 9301123085, Ph. : 4062091
Compiled By: Sandeep Sappal
ii = square<int>(i);
cout << i << ": " << ii << endl;
xx = square<float>(x);
cout << x << ": " << xx << endl;
Class templates
#include<iostream.h>
#include<conio.h>
template <class T>
class TwoNum
{ private:
T x,y;
public:
void getValues()
{
cout<<"Enter Two Numbers:";
cin>>x>>y;
}
void putValues()
{
cout<<x<<","<<y<<endl;
}
T add()
{ T z;
z=x+y; } };
void main()
{Twonum <int>A;
A.getValues();
A.putValues();
int j=A.add();
cout<<j<<endl;
Twonum <double>B;
B.getValues();
B.putValues();
double k=B.add();
cout<<k<<endl; }
Friend Classes
It is often useful for one class to see the private variables of another class, even though these variables should
probably not be made part of the public interface that the class supports.
A friend class in C++ can access the "private" and "protected" members of the class in which it is declared as a
friend.
#include<iostream.h>
#include<conio.h>
class readint
{ 59
13,Gulabchand ki Bagichi, Behind Jhawer Estate, Thatipur Gwl
Mob. : 9301123085, Ph. : 4062091
Compiled By: Sandeep Sappal
float a,b;
public:
void read()
{
cout<<"\n\nEnter the First Number : ";
cin>>a;
cout<<"\n\nEnter the Second Number : ";
cin>>b;
}
friend class sum;
};
class sum
{
public:
float c;
void add(readint rd)
{
c=rd.a+rd.b;
cout<<"\n\nSum="<<c;
}
};
void main()
{
int cont;
readint rd;
sum s;
clrscr();
rd.read();
s.add(rd);
getch();
}
Unformatted I/O opreration generally used to read data from keyboard,memory or file or use to write data in
memory,variable or file.
The general functions which are used for displaying I/O as discusses earlier are ‘<<’ and ‘>>’ with cout and cin.
Some of the other functions used are listed below:
1. get() and put()
• get() is a member function of istream class.
• put is a member function of ostream class.
• get(char *) -> reads single character from the keyboard and assigns to an argument.
• Allow whitespaces & new line character
60
13,Gulabchand ki Bagichi, Behind Jhawer Estate, Thatipur Gwl
Mob. : 9301123085, Ph. : 4062091
Compiled By: Sandeep Sappal
Example:
char c;
cin.get( c); // reads and assigns to c
cout.put(c); //display character
2. getline() and write()
getline()
• getline() function reads the line of text and reading ends when it reaches new line character.
• Allow whitespaces
• Syntax :
• cin.getline(line ,size);
• where ‘line’ is array of character and size is maximum number of characters.
• Ex: char x[30]
cin.getline(x,30); //read string thru keyboard
write()
• The write() method displays entire line on the screen.
• The write methods reads the character by character untill it reaches the new line.
• Syntax :
• cout.write( line ,size);
• Where line is character array and size is number of character to print.
• Ex: char x[]=”Gwalior”;
Cout.write(x,2);// output will be Gw
61
13,Gulabchand ki Bagichi, Behind Jhawer Estate, Thatipur Gwl
Mob. : 9301123085, Ph. : 4062091
Compiled By: Sandeep Sappal
62
13,Gulabchand ki Bagichi, Behind Jhawer Estate, Thatipur Gwl
Mob. : 9301123085, Ph. : 4062091
Compiled By: Sandeep Sappal
Manipulators(iomanip.h)
Manipulators are operators used in C++ for formatting output. The data is manipulated by the programmer’s choice
of display.There are numerous manipulators available in C++. Some of the more commonly used manipulators are
provided here below:
Example:
Cout<<setw(10)<<setfill(‘#’)<<567;
Output
#######567
Cout<<setw(10)<<setfill(‘#’)<<setiosflags(ios::left)<<)567;
Output
567#######
63
13,Gulabchand ki Bagichi, Behind Jhawer Estate, Thatipur Gwl
Mob. : 9301123085, Ph. : 4062091