Beruflich Dokumente
Kultur Dokumente
02/10/2015
Operator overloading:
Refer following program:
#include <iostream>
using namespace std;
class loc {
int longitude, latitude;
388 C + + : T h e C o m p l e t e R e f e r e n c e
public:
loc() {} // needed to construct temporaries
loc(int lg, int lt) {
longitude = lg;
latitude = lt;
}
void show() {
cout << longitude << " ";
cout << latitude << "\n";
}
loc operator+(loc op2);
loc operator-(loc op2);
loc operator=(loc op2);
loc operator++();
};
// Overload + for loc.
loc loc::operator+(loc op2)
{
loc temp;
temp.longitude = op2.longitude + longitude;
temp.latitude = op2.latitude + latitude;
return temp;
}
// Overload - for loc.
loc loc::operator-(loc op2)
{
loc temp;
// notice order of operands
temp.longitude = longitude - op2.longitude;
temp.latitude = latitude - op2.latitude;
return temp;
}
// Overload asignment for loc.
loc loc::operator=(loc op2)
{
longitude = op2.longitude;
latitude = op2.latitude;
return *this; // i.e., return object that generated call
}
// Overload prefix ++ for loc.
loc loc::operator++()
{
longitude++;
latitude++;
return *this;
}
int main()
{
loc ob1(10, 20), ob2( 5, 30), ob3(90, 90);
ob1.show();
ob2.show();
++ob1;
ob1.show(); // displays 11 21
ob2 = ++ob1;
ob1.show(); // displays 12 22
ob2.show(); // displays 12 22
ob1 = ob2 = ob3; // multiple assignment
ob1.show(); // displays 90 90
ob2.show(); // displays 90 90
return 0;
}
2. Prefix and post fix operator over loading:
// Prefix increment
type operator++( ) {
// body of prefix operator
}
// Postfix increment
type operator++(int x) {
// body of postfix operator
}
3. Overloading a shorthand operator:
loc loc::operator+=(loc op2)
{
longitude = op2.longitude + longitude;
latitude = op2.latitude + latitude;
return *this;
}
4. Operator overloading restriction:
4.1 You cannot alter the precedence of an operator.
4.2 You cannot change the number of operands that an operator
takes.
4.3 Except for the function call operator (described later), operator
functions cannot have default arguments.
4.4 Finally, these operators cannot be overloaded: . : : .* ?
5. Friend Function and operator overloading:
In C++, only friend can access private part of the class
You can overload an operator for a class by using a nonmember
function, which is usually a friend of the class. Since a friend function is not
a member of the class, it does not have a this pointer. Therefore, an
overloaded friend operator function is passed the operands explicitly. This
means that a friend function that overloads a binary operator has two
parameters, and a friend function that overloads a unary operator has one
parameter. When overloading a binary operator using a friend function,
the left operand is passed in the first parameter and the right operand is
passed in the second parameter.
In this program, the operator+() function is made into a friend
#include <iostream>
using namespace std;
class loc {
int longitude, latitude;
public:
loc() {} // needed to construct temporaries
loc(int lg, int lt) {
longitude = lg;
latitude = lt;
}
void show() {
cout << longitude << " ";
cout << latitude << "\n";
}
friend loc operator+(loc op1, loc op2); // now a friend
loc operator-(loc op2);
loc operator=(loc op2);
loc operator++();
};
// Now, + is overloaded using friend function.
loc operator+(loc op1, loc op2)
{
loc temp;
temp.longitude = op1.longitude + op2.longitude;
temp.latitude = op1.latitude + op2.latitude;
return temp;
}
// Overload - for loc.
loc loc::operator-(loc op2)
{
loc temp;
// notice order of operands
temp.longitude = longitude - op2.longitude;
temp.latitude = latitude - op2.latitude;
return temp;
}
// Overload assignment for loc.
loc loc::operator=(loc op2)
{
longitude = op2.longitude;
latitude = op2.latitude;
return *this; // i.e., return object that generated call
}
// Overload ++ for loc.
loc loc::operator++()
{
longitude++;
latitude++;
return *this;
}
int main()
{
loc ob1(10, 20), ob2( 5, 30);
ob1 = ob1 + ob2;
ob1.show();
return 0;
}
Friend function for overloading ++
#include <iostream>
using namespace std;
class loc {
int longitude, latitude;
public:
loc() {}
loc(int lg, int lt) {
longitude = lg;
latitude = lt;
}
void show() {
cout << longitude << " ";
cout << latitude << "\n";
}
op.longitude--;
op.latitude--;
return op;
}
int main()
{
loc ob1(10, 20), ob2;
ob1.show();
++ob1;
ob1.show(); // displays 11 21
ob2 = ++ob1;
ob2.show(); // displays 12 22
--ob2;
ob2.show(); // displays 11 21
return 0;
}
Difference between normal overloading and friend function over
loading:
In case of normal operator overloading obj1+100 is possible but
100+obj1 is not possible. But both are possible in case of friend function.
Since in case of normal operator overloading left operator calls the
overloading operator function while in case of friend function we pass both
the object to the function.
Inheritance:
When a class inherits another class then the members of base class
become members of derived class.
Class derived: access-specifier base class{}
Access specifier could be public, private or protected.
If public: all public becomes public, protected becomes protected and
private becomes private.
If protected: all public and protected becomes protected and private
remains private.
If private: all becomes private.
Default access specifier in case of class is private and in case of struct
it is public.
Important points:
1. Multiple inheritance is possible. Class derived : public base1, public
base2{}
2. Constructor and destructor can not be inherited. But only the
constructor and destructor base class gets called for derived object.
Constructing base2
Constructing base1
Constructing derived
Destructing derived
Destructing base1
Destructing base2
3. Parameters can be passed to base class constructor as
derived(int x, int y ): base(y)
4. In case of inheritance, if we want to restore access of some of the
members of the base class that is possible. Consider derived class inherited
the base class as private. But you want variable j to be restore in derived
class then it is possible using either using statement or access
declarationbase-class::member within derived class.
Class base {public: int i;};
in derived3! */
class derived3 : public derived1, public derived2 {
public:
int sum;
};
int main()
{
C h a p t e r 1 6 : I n h e r i t a n c e 439
Remember
derived3 ob;
ob.i = 10; // this is ambiguous,
ob.j = 20;
ob.k = 30;
// i ambiguous here, too
ob.sum = ob.i + ob.j + ob.k;
// also ambiguous, which i?
cout << ob.i << " ";
cout << ob.j << " " << ob.k << " ";
cout << ob.sum;
return 0;
}
In above program derived3 has two copies of base class. To avoid this
ambiguity there are two ways:
1. Use scope resolution operator. So ob.i can be replaced by
ob.derived1::i=10
2. Use of virtual base class. i.e. in definition of derived class just add
virtual before access-specifier as
// derived1 inherits base as virtual.
class derived1 : virtual public base {
public:
int j;
};
// derived2 inherits base as virtual.
class derived2 : virtual public base {
public:
int k;
};
/* derived3 inherits both derived1 and derived2.
This time, there is only one copy of base class. */
class derived3 : public derived1, public derived2 {
public:
int sum;
};
Virtual Function:
For vTable and vptr refer
http://www.go4expert.com/articles/virtual-table-vptr-t16544/
1. Virtual function can be called using base class pointer and base
class reference.
Ex:
Int main(){
base *p, b;
derived d;
p=&b;
//Base class pointer
p.func();
p=&d;
p.func();
return 0;
}
2. Virtual attribute can be inherited.
Class base{public: virtual void func();}
Class derived1: public base{public: void func();}
Class derived2: public derived1{public: void func();} // inherited.
3. Overriding is nothing but virtual function.
4. If a function is defined as the virtual in base and that function is not
defined in derived class and then we called that function using derived class
object then base class function gets called. If there is hierarchy then the
latest definition is called.
Ex. base{virtual void func()}----------- derived1{void func()} -----
derived2.
If object of derived2 tried to access the func() then definition of in
derived class gets called.
5. Pure virtual function. virtual void func()=0; This function need to
have there definition in all of the derived classes.
6.Difference Late Binding vs Early Binding: Late binding are happen in
case of virtual function. This function call are resolved at the run time. While
the early binding happens in case of normal functions. These function are
resolved at compile time.
Templates:
It is feature of C++. Using template generic classes and generic
functions can be created. Templates help us to reduce the redundant code
written just for different data types.
Generic Function:
The function of same logic can be used for different data types. Only
one function definition called generic function. Depending upon the datatype
compiler will process the function at compile time. Generic function are
different from overloaded function as in generic function the action
performed on variable are remain same i.e. logic of then function never
changes only data type changes
Definition:
Template <class X> void func(X a, X b ) { }
where X is data type. X can be int,char,struct,object,etc
Generic class:
Concept is same. Same class definition but can be used with different
data types.
Definition:
Template <data Type> class class-name {}
Inside main function or any function we can called it as
class-name <data Type> d;
Important Notes:
1. Overloading function template for generic function is possible.
Template <class X> void func(X a)
template <class X> void func(X a, X b)
2. Explicitly overloading generic function.
Exception handling:
Process :
Reference:
http://duartes.org/gustavo/blog/post/anatomy-of-a-program-inmemory/
https://www.corelan.be/index.php/2009/07/19/exploit-writing-tutorialpart-1-stack-based-overflows/
http://www.tutorialspoint.com/operating_system/os_process_scheduli
ng.htm
Process:
A process is a program in execution. The execution of a process must
progress in a sequential fashion. Definition of process is following.
A process is defined as an entity which represents the basic unit of
work to be implemented in the system.
Components of process are following.
S.N.
Object Program
Code to be executed.
Data
Data to be used for executing the program.
Resources
While executing the program, it may require some resources.
Status
Verifies the status of the process execution.A process can run
to completion only when all requested resources have been
allocated to the process. Two or more processes could be
executing the same program, each using their own data and
resources.
Program:
A program by itself is not a process. It is a static entity made up of
program statement while process is a dynamic entity. Program contains the
instructions to be executed by processor.
A program takes a space at single place in main memory and
continues to stay there. A program does not perform any action by itself.
As a process executes, it changes state. The state of a process is
defined as the current activity of the process.
Process can have one of the following five states at a time.
S.N.
1
Process in memory:
S.N.
Schedulers:
Schedulers are special system softwares which handles process
scheduling in various ways.Their main task is to select the jobs to be
submitted into the system and to decide which process to run. Schedulers
are of three types
1. Long Term Scheduler
2. Short Term Scheduler
3. Medium Term Scheduler
Long Term Scheduler:
It is also called job scheduler. Long term scheduler determines which
programs are admitted to the system for processing. Job scheduler selects
processes from the queue and loads them into memory for execution.
Process loads into the memory for CPU scheduling. The primary objective of
the job scheduler is to provide a balanced mix of jobs, such as I/O bound
and processor bound. It also controls the degree of multiprogramming. If the
degree of multiprogramming is stable, then the average rate of process
creation must be equal to the average departure rate of processes leaving
the system.
On some systems, the long term scheduler may not be available or
minimal. Time-sharing operating systems have no long term scheduler.
When process changes the state from new to ready, then there is use of long
term scheduler.
Short Term Scheduler
It is also called CPU scheduler. Main objective is increasing system
performance in accordance with the chosen set of criteria. It is the change of
ready state to running state of the process. CPU scheduler selects process
among the processes that are ready to execute and allocates CPU to one of
them.
Short term scheduler also known as dispatcher, execute most
frequently and makes the fine grained decision of which process to execute
next. Short term scheduler is faster than long term scheduler.
Medium Term Scheduler
Medium term scheduling is part of the swapping. It removes the
processes from the memory. It reduces the degree of multiprogramming.
The medium term scheduler is in-charge of handling the swapped outprocesses.
Long Term
S.N. Scheduler
1
Short Term
Scheduler
Medium
Term Scheduler
It is a job
scheduler
It is a CPU
scheduler
It is a process
swapping scheduler.
Speed is
lesser than short
term scheduler
Speed is
fastest among
other two
Speed is in
between both short
and long term
scheduler.
It controls
the degree of
multiprogramming
It provides
lesser control over
degree of
multiprogramming
It reduces the
degree of
multiprogramming.
It is almost
absent or minimal
in time sharing
system
It is also
minimal in time
sharing system
It is a part of
Time sharing
systems.
It selects
processes from
pool and loads
them into memory
for execution
It selects
those processes
which are ready to
execute
Context Switch
A context switch is the mechanism to store and restore the state or
context of a CPU in Process Control block so that a process execution can be
resumed from the same point at a later time. Using this technique a context
switcher enables multiple processes to share a single CPU. Context switching
is an essential part of a multitasking operating system features.
When the scheduler switches the CPU from executing one process to
execute another, the context switcher saves the content of all processor
registers for the process being removed from the CPU, in its process
descriptor. The context of a process is represented in the process control
block of a process.
Context switch time is pure overhead. Context switching can
significantly affect performance as modern computers have a lot of general
and status registers to be saved. Content switching times are highly
dependent on hardware support. Context switch requires ( n + m ) bxK time
units to save the state of the processor with n general registers, assuming b
are the store operations are required to save n and m registers of two
process control blocks and each store instruction requires K time units.
Orphan process:
An orphan process is a computer process whose parent process has
finished or terminated, though it remains running itself.
In a Unix-like operating system any orphaned process will be
immediately adopted by the special initsystem process. This operation is
called re-parenting and occurs automatically. Even though technically the
process has the init process as its parent, it is still called an orphan process
since the process that originally created it no longer exists.
When a process ends, all of the memory and resources associated with
it are deallocated so they can be used by other processes. However, the
process's entry in the process table remains. The parent can read the child's
exit status by executing the wait system call, whereupon the zombie is
removed. The wait call may be executed in sequential code, but it is
commonly executed in a handler for the SIGCHLD signal, which the parent
receives whenever a child has died.
After the zombie is removed, its process identifier (PID) and entry in
the process table can then be reused. However, if a parent fails to call wait,
the zombie will be left in the process table. In some situations this may be
desirable, for example if the parent creates another child process it ensures
that it will not be allocated the same PID. On modern UNIX-like systems
(that comply with SUSv3 specification in this respect), the following special
case applies: if the parent explicitly ignores SIGCHLD by setting its handler
toSIG_IGN (rather than simply ignoring the signal by default) or has
the SA_NOCLDWAIT flag set, all child exit status information will be
discarded and no zombie processes will be left
A zombie process is not the same as an orphan process. An
orphan process is a process that is still executing, but whose parent has
died. They do not become zombie processes; instead, they are adopted
by init (process ID 1), which waits on its children.
Interprocess Communication:
Shared memory:
Message-passing:
Pipes:
Named pipes(FIFO):
Threads:
A thread is a flow of execution through the process code, with
its own program counter, system registers and stack. A thread is also
called a light weight process. Threads provide a way to improve application
performance through parallelism. Threads represent a software approach to
improving performance of operating system by reducing the overhead thread
is equivalent to a classical process.
Each thread belongs to exactly one process and no thread can exist
outside a process. Each thread represents a separate flow of control.
Threads have been successfully used in implementing network servers and
web server. They also provide a suitable foundation for parallel execution of
applications on shared memory multiprocessors. Following figure shows the
working of the single and multithreaded processes.
Process
S.N.
Thread
Advantages of Thread
1.Thread minimize context switching time.
2.Use of threads provides concurrency within a process.
3.Efficient communication.
4.Economy- It is more economical to create and context switch
threads.
5.Utilization of multiprocessor architectures to a greater scale and
efficiency.
Types of Thread
Threads are implemented in following two ways
User Level Threads -- User managed threads
Kernel Level Threads -- Operating System managed threads acting
on kernel, an operating system core.
User Level Threads
In this case, application manages thread management kernel is not
aware of the existence of threads. The thread library contains code for
creating and destroying threads, for passing message and data between
threads, for scheduling thread execution and for saving and restoring thread
contexts. The application begins with a single thread and begins running in
that thread.
ADVANTAGES
1.Thread switching does not require Kernel mode privileges.
2.User level thread can run on any operating system.
3.Scheduling can be application specific in the user level thread.
4.User level threads are fast to create and manage.
DISADVANTAGES
1.In a typical operating system, most system calls are blocking.
2.Multithreaded application cannot take advantage of multiprocessing.
Kernel Level Threads:
In this case, thread management done by the Kernel. There is no
thread management code in the application area. Kernel threads are
supported directly by the operating system. Any application can be
programmed to be multithreaded. All of the threads within an application are
supported within a single process.
The Kernel maintains context information for the process as a whole
and for individuals threads within the process. Scheduling by the Kernel is
done on a thread basis. The Kernel performs thread creation, scheduling and
management in Kernel space. Kernel threads are generally slower to create
and manage than the user threads.
ADVANTAGES
Many to One Model
Many to one model maps many user level threads to one Kernel level
thread. Thread management is done in user space. When thread makes a
blocking system call, the entire process will be blocks. Only one thread can
access the Kernel at a time,so multiple threads are unable to run in parallel
on multiprocessors.
If the user level thread libraries are implemented in the operating
system in such a way that system does not support them then Kernel
threads use the many to one relationship modes.
One to One Model
There is one to one relationship of user level thread to the kernel level
thread.This model provides more concurrency than the many to one model.
It also another thread to run when a thread makes a blocking system call. It
support multiple thread to execute in parallel on microprocessors.
Disadvantage of this model is that creating user thread requires the
corresponding Kernel thread. OS/2, windows NT and windows 2000 use one
to one relationship model.
Difference between User Level & Kernel Level Thread
S
.N.
Implementation is by a thread
library at the user level.
Thread library:
1. POSIX Pthread : for unix
2. Windows Thread
3. Java Thread library
Multicore and multiprocessor CPU and Hyperthreading :
Threading is preferred and encouraged for multicore processor
Multiprocessor CPU: This kind of motherboard will found in
supercomputers and very high performing computers. But this is not suitable
as hardware requirement is very high.
Note: Please read ppt on multicore arch which is stored in drive.
Thread Pool:
In case of multithreaded web server whenever the server receives a
request, it creates a separate thread to service the request. Whereas
creating a separate thread is certainly superior to creating a separate
process, a multithreaded server nonetheless has potential problems. The
first issue concerns the amount of time required to create the thread,
together with the fact that the thread will be discarded once it has
completed its work. The second issue is more troublesome. If we allow all
concurrent requests to be serviced in a new thread, we have not placed a
bound on the number of threads concurrently active in the system. Unlimited
threads could exhaust system resources, such as CPU time or memory. One
solution to this problem is to use a thread pool.
The general idea behind a thread pool is to create a number of threads
at
process startup and place them into a pool, where they sit and wait for
work.
When a server receives a request, it awakens a thread from this pool
if one
is availableand passes it the request for service. Once the thread
completes its service, it returns to the pool and awaits more work. If the
pool contains no available thread, the server waits until one becomes free.
Threading Issues:
1 The fork() and exec() System Calls:
5. Scheduler activations:
A final issue to be considered with multithreaded programs concerns
communication between the kernel and the thread library, which may be
required by the many-to-many and two-level models. Such coordination
allows the number of kernel threads to be dynamically adjusted to help
ensure the best performance.
Many systems implementing either the many-to-many or the two-level
model place an intermediate data structure between the user and
kernel
threads. This data structuretypically known as a lightweight process,
or
LWPis shown in Figure. To the user-thread library, the LWP appears
to be a virtual processor on which the application can schedule a user thread
to run. Each LWP is attached to a kernel thread, and it is kernel threads that
the
Process Synchronization:
Process synchronization are required in case of cooperating process
where multiple process are working simultaneously. Consider two process
which are modifying common data structure. That common data structure is
nothing but critical section which can affect performance of the other
process. To avoid that process synchronization is required.
Process synchronization techniques:
Reference:
http://www2.cs.uregina.ca/~hamilton/courses/330/notes/synchro/node3.ht
ml
1. Petersons solution(Software approach):
2. Mutex
3. Semaphore: (Binary or counting semaphore)
typedef struct {
int value;
struct process *list;
} semaphore;
wait(semaphore *S) {
S->value--;
if (S->value < 0) {
add this process to S->list;
block();
}
}
signal(semaphore *S) {
S->value++;
if (S->value <= 0) {
remove a process P from S->list;
wakeup(P);
}
}
Deadlock and Starvation:
Because of deadlock starvation can happen. Infinitely blocking process
is a starved process.
Synchronization Problem:
1. Bounded buffer problem
2. Reader Writer problm
3. Dining philosopher problem
Usage of Monitor:
Operator
Associa
tivity
() [] -> . ++ - -
Left to
right
Unary
Right to
left
Multiplic
*/%
ative
Left to
right
Additive
+-
Left to
right
Shift
<< >>
Left to
right
Relation
al
Left to
right
Equality
== !=
Left to
right
Bitwise
&
AND
Left to
right
Bitwise
XOR
Left to
right
Bitwise
OR
Left to
right
Logical
&&
AND
Left to
right
Logical
||
OR
Left to
right
Conditio
?:
nal
Right to
left
Assignm
ent
Comma
Right to
left
Left to
right