Sie sind auf Seite 1von 57

INDUSTRIAL TRAINING REPORT

ON
C++ in UNIX Software Development

Submitted in partial fulfillment of the requirements for the award of


Degree of Bachelor of Technology (M.D. University, Rohtak) in
Electronics and Communication Engineering
(2014-15)

SUBMITTED BY:
NAME: Arjun Butola
UNIVERSITY ROLL NO.____________
UNDER THE GUIDANCE OF:
(Rahul Butola)
(Technical Architect Genband Association)
(GlobalLogic India Pvt. Ltd.)

Prof. (Dr.) H.S. Dua


HOD (ECE)

DEPT OF ELECTRONICS & COMMUNICATION ENGINEERING


DRONACHARYA COLLEGE OF ENGINEERING
FARRUKH NAGAR, GURGAON

TABLE OF CONTENTS
DECLARATION...............................................................................................................................4
CERTIFICATE FROM THE COMPANY/ORGANISATION........................................................5
CERTIFICATE.................................................................................................................................6
ACKNOWLEDGEMENT................................................................................................................7
List of Abbreviations........................................................................................................................8
EXECUTIVE SUMMARY...............................................................................................................9
1

About GlobalLogic..................................................................................................................10

Introduction..............................................................................................................................11

2.1

Comparison of Open Source and Closed Source......................................................................

2.2

Code Quality.............................................................................................................................

UNIX.......................................................................................................................................13
3.1

UNIX and its Components.......................................................................................................

3.2

Effect of UNIX on the world....................................................................................................

3.3

Free UNIX and UNIX-like Operating Systems.......................................................................

3.4

ARPANET................................................................................................................................

3.5

List of UNIX Systems..............................................................................................................

3.6

AT&T UNIX Systems and Descendents..................................................................................

C++...........................................................................................................................................
4.1

History of C++.........................................................................................................................

4.2

Philosophy................................................................................................................................

4.3

Languages.................................................................................................................................

4.4

Operators and Operator Overloading.......................................................................................

4.5

Object Storage..........................................................................................................................

4.6

Static Storage Duration Objects...............................................................................................

4.7

Thread Storage Duration Objects.............................................................................................

4.8

Dynamic Storage Duration Objects..........................................................................................

4.9

Threading..................................................................................................................................

Observer Design Pattern..................................32


5.1

Intent32

5.2

Problem32

5.3

Discussion32
2

5.4

Structure33

5.5

Checklist34

5.6

Rules of Thumb35

5.7

Observer Design Pattern35

5.8

Observer Pattern38

5.9

Variations50

N-ary Tree..51
6.1

Types of N-ary Tree51

6.2

Structure of N-ary Tree52

6.3

Algorith for Deletion of a Node55

Conclusion..56

Bibliography..57

DECLARATION

I, Mr. Arjun Butola hereby declare that this project report is the record of authentic work being
carried out by me during the period from 5 th January, 2015 to 5th July, 2015 and has not been
submitted to any other University or Institute for the award of any degree/diploma etc.

Arjun Butola
Roll No.:
Date:

CERTIFICATE FROM THE COMPANY/ORGANISATION

(On the letterhead of the Company/ Organisation, given and signed by the concerned
authority in the Company / Organisation where student has done the Summer Training. It
should also have Company/ Organisation Seal /Stamp.)

CERTIFICATE

T h i s i s t o c e r t i f y t h a t M r. Ar j u n B u t o l a o f D r o n a c h a r ya C o l l e g e o f
Engineering, Gurgaon has successfully completed the project work titled
C++

in

UNIX

Software

Development

in

partial

fulfillment

r e q u i r e m e n t f o r t h e c o m p l e t i o n o f B a c h e l o r o f Tec h n o l o g y a s

of

prescribed

b y t h e M a h a r i s h i D a ya n a d U n i v e r s i t y, R o h t a k .
This project report is the record of authentic work arried out by him
d u r i n g t h e p e r i o d f r o m 5 t h J a n u a r y, 2 0 1 5 t o 5 t h J u l y, 2 0 1 5 .
He has worked under my guidance.

Mr. Rahul Butola


(Technical Architect Genband Association)
GlobalLogic India Pvt. Ltd.
Project Guide (Internal)
Date:
Signature
Name
Principal/
HOD
Date:

ACKNOWLEDGEMENT

It gives me immense pleasure to express my gratitude towards Mr. Rahul Butola for giving me an
opportunity to work in this Organization, under his able guidance and encouragement. His
constructive suggestions and continuous guidance has always encouraged me to put in my best and
complete my work in due time.
I also express my gratitude to the GlobalLogic administration for their valuable time and
explaining to me the minor details of the technology involved.

Arjun Butola
Date:

List of Abbreviations
Abbreviation

Full form

P-Thread

Posix Thread

N-ary

N-ary Tree

B-ary

Binary Tree

MATLAB

Matrix Labotary

sh

shell

OS

Operating System

EXECUTIVE SUMMARY
Following the trailblazing and evergreen scope of Software Development I developed a thorough
interest for a deep know-how of C++ coding in LINUX.
GlobalLogic provided me with a comfortable platform by experimenting on their patented
company tools for creating public platform projects as a contribution to the companys mainline
resources.
Programming in GNC G++ compiler I worked under the two aspects of

Observer Pattern
N-ary Trees

Which are both used in day to day life software requirements. Trying to develop hypothetical
concepts into real world simuation I hereby present my internship experience in the following
report titled C++ in UNIX

1. About GlobalLogic
GlobalLogic combines cross-industry expertise and experience with market-defining customers to
make connections between makers and markets worldwide. Theyve gained unique insight from
working on innovative products and disruptive technologies that they share with business leaders,
showing them how strategic research and development can become a tool for managing their
future. GlobalLogic uses the power of connection to help them make amazing products, discover
new revenue opportunities, and accelerate time-to-market.
For their customers, connection means connecting the dotsnot only between different stages of
the product lifecycle, but also between business opportunities the customers might not have seen
otherwise. They know from experience that different products require different product
development approaches. For example, where one product might benefit from a compressed R&D
cycle, another might realize efficiencies through automated testing. They also know that even the
most forward-thinking companies dont always see opportunities outside of their original
strategies. For those customers, we connect the dots between revenue, innovation, and new global
markets.
Their commitment doesnt end once theyve made connections between our customers and global
markets. Once theyve engaged with a customerwhether working as project-based teams or as
carefully assembled in-house labsour employees take pride of ownership in the products they
help design, develop, test, and support. They call this shared responsibility. Many of their
customers consider their GlobalLogic experts to be inseparable from their own product
development teams, and GlobalLogic does everything possible to maintain the trust that has led to
many productive, long-term relationships with industry leaders.

10

2. INTRODUCTION
2.1 COMPARISON OF OPEN SOURCE AND CLOSED SOURCE
2.1.1 Innovation
The implementation of compatible FOSS replacements for proprietary software is encouraged by
the Free Software Foundation to make it possible for their users to use FOSS instead of proprietary
software, for example they have been listed GNU Octave, an API-compatible replacement for
MATLAB, as one of their high priority projects, in the past this list contained free binary
compatible Java and CLI implementations, like GNU Classpath and DotGNU. Thus even
"derivative" developments are important in the opinion of many people from FOSS. However,
there is no quantitative analysis, if FOSS is less innovative than proprietary software, since there
are derivative/re-implementing proprietary developments, too.
Some of the largest well-known FOSS projects are either legacy code (e.g., FreeBSD or Apache)
developed a long time ago independently of the free software movement, or by companies like
Netscape (which open-sourced its code with the hope that they can compete better), or by
companies like MySQL which use FOSS to lure customers for its more expensive licensed product.
However, it is notable that most of these projects have seen major or even complete rewrites (in the
case of the Mozilla and Apache 2 code, for example) and do not contain much of the original code.
Innovations have come, and continue to come, from the open-source world:

GmailFS is a good example of the collaborative nature of much open-source development.


Building on FUSE (which allows filesystems to be implemented in userspace, instead of as
code that needs to be loaded into the kernel) combined with libgmail, which is a Python
library for programmatic access to a user's Gmail message store, the result is the ability to
use the multiple gigabytes of Gmail message space as a fileserver accessible from

anywhere on the Internet.


Perl, the pioneering open-source scripting language, made popular many features, like
regular expressions and associative arrays that were unusual at the time. The newer Python
language continues this innovation, with features like functional constructs and class-

dictionary unification.
dcraw is an open-source tool for decoding RAW-format images from a variety of digital
cameras, which can produce better images than the closed-source tools provided by the
camera vendors themselves.
11

A number of laptop models are available with a particular emphasis on multimedia


capabilities. While these invariably come preinstalled with a copy of Microsoft Windows,
some of them also offer an alternative "fast-boot" mode (such as Phoenix HyperSpace)

based on GNU/Linux. This gets around the long time it can take to boot up Windows.
VLC media player, Songbird, and Amarok are FOSS music players that integrate internetbased data sources to an unprecedented degree, taking song information from MusicBrainz,
related track information from last.fm, album cover art from amazon.com and displaying an

artist's Wikipedia page within the player.


While admittedly inspired by Mac OS X's Quartz graphics layer, Compiz Fusion has
pioneered the concept of "plug in" window decorators and animation effects. Users can

develop their own creative and unique effects.


Open-source telecommunication products, such as the Asterisk PBX, have revolutionized

the ICT industry.


There are substantial efforts towards the implementation of a semantic desktop in FOSS

communities.
Today's desktop environments are innovating regarding their unique idea of a Social

Desktop.
Many academic research projects release their results as FOSS.

2.2 CODE QUALITY


An analysis of the code of the FreeBSD, Linux, Solaris, and Windows operating system kernels
looked for differences between code developed using open-source properties (the first two kernels)
and proprietary code (the other two kernels). The study collected metrics in the areas of file
organization, code structure, code style, the use of the C preprocessor, and data organization. The
aggregate results indicate that across various areas and many different metrics, four systems
developed using open- and closed-source development processes score comparably. The study
mentioned above is refuted by a study conducted by Coverity, Inc finding open source code to be
of better quality.

3. UNIX
12

UNIX (all-caps UNIX for the trademark) is a family of multitasking, multiuser computer operating
systems that derive from the original AT&T UNIX, developed in the 1970s at the Bell Labs
research center by Ken Thompson, Dennis Ritchie, and others.
Initially intended for use inside the Bell System, AT&T licensed UNIX to outside parties from the
late 1970s, leading to a variety of both academic and commercial variants of UNIX from vendors
such as the University of California, Berkeley (BSD), Microsoft (Xenix), IBM (AIX) and Sun
Microsystems (Solaris). AT&T finally sold its rights in UNIX to Novell in the early 1990s, which
then sold its UNIX business to the Santa Cruz Operation (SCO) in 1995, but the UNIX trademark
passed to the industry standards consortium The Open Group.
UNIX systems are characterized by a modular design that is sometimes called the "Unix
philosophy", meaning that the operating system provides a set of simple tools that each perform a
limited, well-defined function, with a unified file system as the main means of communication and
a shell scripting and command language to combine the tools to perform complex workflows.
Aside from the modular design, UNIX also distinguishes itself from its predecessors as the first
portable operating system: virtually, the entire operating system is written in the C programming
language that allowed it to outgrow the 16-bit PDP-11 minicomputer for which it was originally
developed.
Originally, UNIX was meant to be a programmer's workbench to be used for developing software
to be run on multiple platforms more than to be used to run application software. The system grew
larger as the operating system started spreading in the academic circle, as users added their own
tools to the system and shared them with colleagues.
UNIX was designed to be portable, multi-tasking and multi-user in a time-sharing configuration.
Unix systems are characterized by various concepts: the use of plain text for storing data; a
hierarchical file system; treating devices and certain types of inter-process communication (IPC) as
files; and the use of a large number of software tools, small programs that can be strung together
through a command-line interpreter using pipes, as opposed to using a single monolithic program
that includes all of the same functionality. These concepts are collectively known as the "Unix
philosophy". Brian Kernighan and Rob Pike summarize this in The UNIX Programming
Environment as "the idea that the power of a system comes more from the relationships among
programs than from the programs themselves".
13

Fig 1. The Common Desktop Environment (CDE), part of the COSE initiative
Beginning in the late 1980s, an open operating system standardization effort now known as POSIX
provided a common baseline for all operating systems; IEEE based POSIX around the common
structure of the major competing variants of the UNIX system, publishing the first POSIX standard
in 1988. In the early 1990s, a separate but very similar effort was started by an industry
consortium, the Common Open Software Environment (COSE) initiative, which eventually
became the Single UNIX Specification administered by The Open Group. Starting in 1998, the
Open Group and IEEE started the Austin Group, to provide a common definition of POSIX and the
Single UNIX Specification.
In 1999, in an effort towards compatibility, several UNIX system vendors agreed on SVR4's
Executable and Linkable Format (ELF) as the standard for binary and object code files. The
common format allows substantial binary compatibility among UNIX systems operating on the
same CPU architecture.
14

The File system Hierarchy Standard was created to provide a reference directory layout for Unixlike operating systems, and has mainly been used in Linux.
3.1 UNIX AND ITS COMPONENTS
The UNIX system is composed of several components that are normally packaged together. By
including the development environment, libraries, documents and the portable, modifiable source
code for all of these components, in addition to the kernel of an operating system, UNIX was a
self-contained software system. This was one of the key reasons it emerged as an important
teaching and learning tool and has had such a broad influence.
The inclusion of these components did not make the system large the original V7 UNIX
distribution, consisting of copies of all of the compiled binaries plus all of the source code and
documentation occupied less than 10 MB and arrived on a single nine-track magnetic tape. The
printed documentation, typeset from the on-line sources, was contained in two volumes.
The names and file system locations of the UNIX components have changed substantially across
the history of the system. Nonetheless, the V7 implementation is considered by many to have the
canonical early structure:
Kernel source code in /usr/sys, composed of several sub-components:

conf configuration and machine-dependent parts, including boot code


dev device drivers for control of hardware (and some pseudo-hardware)
sys operating system "kernel", handling memory management, process scheduling,

system calls, etc.


h header files, defining key structures within the system and important system-specific
invariables

Development environment early versions of UNIX contained a development environment


sufficient to recreate the entire system from source code:

cc C language compiler (first appeared in V3 Unix)


as machine-language assembler for the machine
ld linker, for combining object files
lib object-code libraries (installed in /lib or /usr/lib). libc, the system library with C runtime support, was the primary library, but there have always been additional libraries for
such things as mathematical functions (libm) or database access. V7 Unix introduced the
first version of the modern "Standard I/O" library stdio as part of the system library. Later
implementations increased the number of libraries significantly.
15

make build manager (introduced in PWB/UNIX), for effectively automating the build

process
include header files for software development, defining standard interfaces and system
invariants

Other languages V7 Unix contained a Fortran-77 compiler, a programmable arbitrary-precision


calculator (bc, dc), and the awk scripting language; later versions and implementations contain
many other language compilers and toolsets. Early BSD releases included Pascal tools, and many
modern UNIX systems also include the GNU Compiler Collection as well as or instead of a
proprietary compiler system.
Other tools including an object-code archive manager (ar), symbol-table lister (nm), compilerdevelopment tools (e.g. lex & yacc), and debugging tools.
Commands UNIX makes little distinction between commands (user-level programs) for system
operation and maintenance (e.g. cron), commands of general utility (e.g. grep), and more generalpurpose applications such as the text formatting and typesetting package. Nonetheless, some major
categories are:

sh the "shell" programmable command-line interpreter, the primary user interface on


Unix before window systems appeared, and even afterward (within a "command window").

Utilities the core toolkit of the UNIX command set, including cp, ls, grep, find and many others.
Subcategories include:
System utilities administrative tools such as mkfs, fsck, and many others.
User utilities environment management tools such as passwd, kill, and others.
Document formatting Unix systems were used from the outset for document preparation and
typesetting systems, and included many related programs such as nroff, troff, tbl, eqn, refer, and
pic. Some modern Unix systems also include packages such as TeX and Ghostscript.
Graphics the plot subsystem provided facilities for producing simple vector plots in a deviceindependent format, with device-specific interpreters to display such files. Modern Unix systems
also generally include X11 as a standard windowing system and GUI, and many support OpenGL.
Communications early UNIX systems contained no inter-system communication, but did include
the inter-user communication programs mail and write. V7 introduced the early inter-system
communication system UUCP, and systems beginning with BSD release 4.1c included TCP/IP
utilities.
16

Documentation UNIX was the first operating system to include all of its documentation online in
machine-readable form. The documentation included:

man manual pages for each command, library component, system call, header file, etc.
doc longer documents detailing major subsystems, such as the C language and troff

3.2 EFFECT OF UNIX ON THE WORLD


The UNIX system had significant impact on other operating systems. It won its success by:

Direct interaction.
Providing the software at a nominal fee for educational use.
Running on inexpensive hardware.
Being easy to adapt and move to different machines.

It was written in a high level language rather than assembly language (which had been thought
necessary for systems implementation on early computers). Although this followed the lead of
Multics and Burroughs, it was UNIX that popularized the idea.
UNIX had a drastically simplified file model compared to many contemporary operating systems:
treating all kinds of files as simple byte arrays. The file system hierarchy contained machine
services and devices (such as printers, terminals, or disk drives), providing a uniform interface, but
at the expense of occasionally requiring additional mechanisms such as ioctl and mode flags to
access features of the hardware that did not fit the simple "stream of bytes" model. The Plan 9
operating system pushed this model even further and eliminated the need for additional
mechanisms.
UNIX also popularized the hierarchical file system with arbitrarily nested subdirectories, originally
introduced by Multics. Other common operating systems of the era had ways to divide a storage
device into multiple directories or sections, but they had a fixed number of levels, often only one
level. Several major proprietary operating systems eventually added recursive subdirectory
capabilities also patterned after Multics. DEC's RSX-11M's "group, user" hierarchy evolved into
VMS directories, CP/M's volumes evolved into MS-DOS 2.0+ subdirectories, and HP's MPE
group, account hierarchy and IBM's SSP and OS/400 library systems were folded into broader
POSIX file systems.
Making the command interpreter an ordinary user-level program, with additional commands
provided as separate programs, was another Multics innovation popularized by UNIX.
The UNIX shell used the same language for interactive commands as for scripting (shell scripts
there was no separate job control language like IBM's JCL). Since the shell and OS commands
17

were "just another program", the user could choose (or even write) his own shell. New commands
could be added without changing the shell itself. UNIXs innovative command-line syntax for
creating modular chains of producer-consumer processes (pipelines) made a powerful
programming paradigm (co-routines) widely available. Many later command-line interpreters have
been inspired by the UNIX shell.
A fundamental simplifying assumption of UNIX was its focus on newline-delimited text for nearly
all file formats. There were no "binary" editors in the original version of UNIX the entire system
was configured using textual shell command scripts. The common denominator in the I/O system
was the byte unlike "record-based" file systems. The focus on text for representing nearly
everything made UNIX pipes especially useful, and encouraged the development of simple,
general tools that could be easily combined to perform more complicated ad hoc tasks. The focus
on text and bytes made the system far more scalable and portable than other systems. Over time,
text-based applications have also proven popular in application areas, such as printing languages
(PostScript, ODF), and at the application layer of the Internet protocols, e.g., FTP, SMTP, HTTP,
SOAP, and SIP.
UNIX popularized a syntax for regular expressions that found widespread use. The Unix
programming interface became the basis for a widely implemented operating system interface
standard (POSIX, see above).
The C programming language soon spread beyond UNIX, and is now ubiquitous in systems and
applications programming.
Early UNIX developers were important in bringing the concepts of modularity and reusability into
software engineering practice, spawning a "software tools" movement. Over time, the leading
developers of UNIX (and programs that ran on it) established a set of cultural norms for
developing software, norms which became as important and influential as the technology of UNIX
itself; this has been termed the UNIX philosophy.
The TCP/IP networking protocol was quickly implemented on widely used versions of UNIX on
relatively inexpensive computers, which contributed to the Internet explosion of worldwide realtime connectivity, and which formed the basis for implementations on many other platforms.
The Unix policy of extensive on-line documentation and (for many years) ready access to all
system source code raised programmer expectations, and contributed to the 1983 launch of the free
software movement.
18

3.3 FREE UNIX AND UNIX-LIKE OPERATING SYSTEMS


In 1983, Richard Stallman announced the GNU project, an ambitious effort to create a free
software Unix-like system. The GNU project's own kernel development project, GNU Hurd, had
not produced a working kernel, but in 1991 Linus Torvalds released the Linux kernel as free
software under the GNU General Public License. In addition to their use in the Linux operating
system, many GNU packages such as the GNU Compiler Collection (and the rest of the GNU
toolchain), the GNU C library and the GNU core utilities have gone on to play central roles in
other free Unix systems as well.
Linux distributions, consisting of the Linux kernel and large collections of compatible software
have become popular both with individual users and in business. Popular distributions include Red
Hat Enterprise Linux, Fedora, SUSE Linux Enterprise, openSUSE, Debian GNU/Linux, Ubuntu,
Linux Mint, Mandriva Linux, Slackware Linux, MEPIS, and Gentoo.
A free derivative of BSD Unix, 386BSD, was released in 1992 and led to the NetBSD and
FreeBSD projects. With the 1994 settlement of a lawsuit brought against the University of
California and Berkeley Software Design Inc. (USL v. BSDi) by UNIX Systems Laboratories, it
was clarified that Berkeley had the right to distribute BSD Unix for free, if it so desired. Since
then, BSD Unix has been developed in several different product branches, including OpenBSD and
DragonFly BSD.
Linux and BSD are increasingly filling the market needs traditionally served by proprietary UNIX
operating systems, as well as expanding into new markets such as the consumer desktop and
mobile and embedded devices. Because of the modular design of the UNIX model, sharing
components is relatively common; consequently, most or all UNIX and Unix-like systems include
at least some BSD code, and some systems also include GNU utilities in their distributions.
OpenSolaris was the open-source counterpart to Solaris developed by Sun Microsystems, which
included a CDDL-licensed kernel and a primarily GNU userland. However, Oracle discontinued
the project upon their acquisition of Sun, which prompted a group of former Sun employees and
members of the OpenSolaris community to fork OpenSolaris into the illumos kernel. As of 2014,
illumos remains the only active open-source System V derivative.
3.4 ARPANET
19

In May 1975, RFC 681 described the development of Network Unix by the Center for Advanced
Computation at the University of Illinois. The system was said to "present several interesting
capabilities as an ARPANET mini-host". At the time UNIX required a license from Bell
Laboratories that at $20,000(US) was very expensive for non-university users, while an
educational license cost just $150. It was noted that Bell was "open to suggestions" for an
ARPANET-wide license.
Specific features found beneficial were:

Local processing facilities.


Compilers.
Editor.
Document preparation system.
Efficient file system and access control.
Mountable and de-mountable volumes.
Unified treatment of peripherals as special files.
The network control program (NCP) was integrated within the Unix file system.
Network connections treated as special files which can be accessed through standard Unix

I/O calls.
The system closes all files on program exit.
"Desirable to minimize the amount of code added to the basic Unix kernel".

3.5 LIST OF UNIX SYSTEMS


3.5.1 Research UNIX

Ken's new system (Unix) (1969)


UNIX Time-Sharing System v1 (1971)
UNIX Time-Sharing System v2 (1972)
UNIX Time-Sharing System v3 (1973)
UNIX Time-Sharing System v4 (1973)
UNIX Time-Sharing System v5 (1974)
o UNSW 01 (1978)
UNIX Time-Sharing System v6 (1975)
o MINI-UNIX (1977)
o PWB/UNIX 1.0 (1977)
USG 1.0
CB UNIX 1
UNIX Time-Sharing System v7 (1979)
o Unix System III (1981)
UNIX Time-Sharing System v8 (1985)
20

UNIX Time-Sharing System v9 (1986)


UNIX Time-Sharing System v10 (1989)

After the release of Version 10, the UNIX research team at Bell Labs turned its focus to Plan 9
from Bell Labs, a distinct operating system that was first released to the public in 1993.
3.6 AT&T UNIX SYSTEMS AND DESCENDANTS
Each of the systems in this list is evolved from the version before, with Unix System III evolving
from both the UNIX Time-Sharing System v7 and the descendants of the UNIX Time-Sharing
System v6.

UNIX System III (1981)


UNIX System IV (1982)
UNIX System V (1983)
o UNIX System V Release 2 (1984)
o UNIX System V Release 3.0 (1986)
o UNIX System V Release 3.2 (1987)
o UNIX System V Release 4 (1988)
o UNIX System V Release 4.2 (1992)
UnixWare 1.1 (1993)
o UnixWare 1.1.1 (1994)
UnixWare 2.0 (1995)
o UnixWare 2.1 (1996)
UnixWare 2.1.2 (1996)
UnixWare 7 (System V Release 5) (1998)
o UnixWare 7.0.1 (1998)
UnixWare 7.1 (1999)
o UnixWare 7.1.1 (1999)
o UnixWare NSC 7.1+IP (2000)
o UnixWare NSC 7.1+LKP (2000)
o UnixWare NSC 7.1DCFS (2000)
Open Unix 8 (UnixWare 7.1.2) (2001)
o Open Unix 8MP1 (2001)
o Open Unix 8MP2 (2001)
o Open Unix 8MP3 (2002)
o Open Unix 8MP4 (2002)
SCO UnixWare 7.1.3 (2002)
o SCO UnixWare 7.1.3 Update Pack 1 (2003)
o SCO UnixWare 7.1.4 (2004)

21

Fig 2 Debian 6.0


4. C++
C++ (pronounced as cee plus plus) is a general-purpose programming language. It has imperative,
object-oriented and generic programming features, while also providing the facilities for low-level
memory manipulation.
It is designed with a bias toward system programming (e.g., for use in embedded systems or
operating system kernels), with performance, efficiency and flexibility of use as its design
requirements. C++ has also been found useful in many other contexts, including desktop
applications, servers (e.g. e-commerce, web search or SQL servers), performance-critical
applications (e.g. telephone switches or space probes), and entertainment software. C++ is a
compiled language, with implementations of it available on many platforms and provided by
various organizations, including the FSF, LLVM, Microsoft and Intel.
C++ is standardized by the International Organization for Standardization (ISO), with the latest
(and current) standard version ratified and published by ISO in December 2014 as ISO/IEC
14882:2014 (informally known as C++14). The C++ programming language was initially
standardized in 1998 as ISO/IEC 14882:1998, which was then amended by the C++03, ISO/IEC
14882:2003, standard. The current C++14 standard supersedes these and C++11, with new features
and an enlarged standard library. Before the initial standardization in 1998, C++ was developed by
Bjarne Stroustrup at Bell Labs, starting in 1979, who wanted an efficient flexible language (like the
C language), which also provided high-level features for program organization.
22

Many other programming languages have been influenced by C++, including C#, Java, and newer
versions of C (after 1998).
4.1 History of C++
Bjarne Stroustrup, a Danish computer scientist, began his work on C++'s predecessor "C with
Classes" in 1979. The motivation for creating a new language originated from Stroustrup's
experience in programming for his Ph.D. thesis. Stroustrup found that Simula had features that
were very helpful for large software development, but the language was too slow for practical use,
while BCPL was fast but too low-level to be suitable for large software development. When
Stroustrup started working in AT&T Bell Labs, he had the problem of analyzing the UNIX kernel
with respect to distributed computing. Remembering his Ph.D. experience, Stroustrup set out to
enhance the C language with Simula-like features. C was chosen because it was general-purpose,
fast, portable and widely used. As well as C and Simula's influences, other languages also
influenced C++, including, ALGOL 68, Ada, CLU and ML.
Initially, the class, derived class, strong typing, inlining, and default argument features were added
to C via Stroustrup's "C with Classes" to C compiler, Cpre.
In 1983, it was renamed from C with Classes to C++ (++ being the increment operator in C). New
features were added including virtual functions, function name and operator overloading,
references, constants, type-safe free-store memory allocation (new/delete), improved type
checking, and BCPL style single-line comments with two forward slashes (//), as well as the
development of a proper compiler for C++, Cfront.
In 1985, the first edition of The C++ Programming Language was released, which became the
definitive reference for the language, as there was not yet an official standard. The first commercial
implementation of C++ was released in October of the same year.
In 1989, C++ 2.0 was released, followed by the updated second edition of The C++ Programming
Language in 1991. New features in 2.0 included multiple inheritance, abstract classes, static
member functions, const member functions, and protected members. In 1990, The Annotated C++
Reference Manual was published. This work became the basis for the future standard. Late feature
additions included templates, exceptions, namespaces, new casts, and a boolean type.
After the 2.0 update, C++ evolved relatively slowly. In 2011, C++11 standard was released, adding
numerous new features, enlarging the standard library further, and providing more facilities to C++
programmers. After a minor C++14 update, released in December 2014, various new additions are
planned for 2017.
23

4.2 Philosophy
Throughout C++'s life, its development and evolution has been informally governed by a set of
rules that its evolution should follow:

It must be driven by actual problems and its features should be useful immediately in real

world programs.
Every feature should be implementable (with a reasonably obvious way to do so).
Programmers should be free to pick their own programming style, and that style should be

fully supported by C++.


Allowing a useful feature is more important than preventing every possible misuse of C++.
It should provide facilities for organising programs into well-defined separate parts, and

provide facilities for combining separately developed parts.


No implicit violations of the type system (but allow explicit violations that have been

explicitly asked for by the programmer).


Make user created types have equal support and performance to built in types.
Any features that you do not use you do not pay for (e.g. in performance).
There should be no language beneath C++ (except assembly language).
C++ should work alongside other pre-existing programming languages, rather than being

part of its own separate and incompatible programming environment.


If what the programmer wants to do is unknown, allow the programmer to specify (provide
manual control).

4.3 LANGUAGE
C++ inherits most of C's syntax. The following is Bjarne Stroustrup's version of the Hello world
program that uses the C++ Standard Library stream facility to write a message to standard output:
#include <iostream>
int main()
{
std::cout << "Hello, world!\n";
}
Within functions that define a non-void return type, failure to return a value before control reaches
the end of the function results in undefined behavior (compilers typically provide the means to
issue a diagnostic in such a case). The sole exception to this rule is the main function, which
implicitly returns a value of zero.
4.4 Operators and operator overloading
24

C++ provides more than 35 operators, covering basic arithmetic, bit manipulation, indirection,
comparisons, logical operations and others. Almost all operators can be overloaded for userdefined types, with a few notable exceptions such as member access (. and .*) as well as the
conditional operator. The rich set of overloadable operators is central to making user-defined types
in C++ seem like built-in types. Overloadable operators are also an essential part of many
advanced C++ programming techniques, such as smart pointers. Overloading an operator does not
change the precedence of calculations involving the operator, nor does it change the number of
operands that the operator uses (any operand may however be ignored by the operator, though it
will be evaluated prior to execution). Overloaded "&&" and "||" operators lose their short-circuit
evaluation property.

4.5 Object storage


C++ supports four types of memory management:

Static storage duration objects


Thread storage duration objects
Automatic storage duration objects
Dynamic storage duration objects

4.6 Static storage duration objects


Static storage duration objects are created before main() is entered (see exceptions below) and
destroyed in reverse order of creation after main() exits. The exact order of creation is not specified
by the standard (though there are some rules defined below) to allow implementations some
freedom in how to organize their implementation. More formally, objects of this type have a
lifespan that "shall last for the duration of the program".

25

Static storage duration objects are initialized in two phases. First, "static initialization" is
performed, and only after all static initialization is performed, "dynamic initialization" is
performed:
Static initialization all objects are first initialized with zeros. After that, all objects that have a
constant initialization phase are initialized with the constant expression (i.e. variables initialized
with a literal or constexpr). Though it is not specified in the standard, this phase can be completed
at compile time and saved in the data partition of the executable.
Dynamic initialization all object initialization that is done via a constructor or function call
(unless the function is marked with constexpr, in C++11). The dynamic initialization order is
defined as the order of declaration within the compilation unit (i.e. the same file). No guarantees
are provided about the order of initialization between compilation units.
4.7 Thread storage duration objects
Variables of this type are very similar to Static Storage duration objects. The main difference is the
creation time is just prior to thread creation and destruction is done after the thread has been joined.
Automatic storage duration objects
These are the most common type of variable in C++:

local variables inside a function/block.


temporary variables.

The common feature about automatic variables is that they have a lifespan that is limited to the
scope of the variable. They are created and potentially initialized at the point of declaration (see
below for details) and destroyed in the reverse order of creation when the scope is left.
Local variables are created as the point of execution passes the declaration point. If the variable has
a constructor or initializer this is used to define the initial state of the object. Local variables are
destroyed when the local block or function that they are declared in is closed.
Member variables are created when the parent object is created. Array members are initialized
from 0 to the last member of the array in order. Member variables are destroyed when the parent
object is destroyed in the reverse order of creation. i.e. If the parent is an "automatic object" then it
will be destroyed when it goes out of scope which triggers the destruction of all its members.
Temporary variables are created as the result of expression evaluation and are destroyed when the
statement containing the expression has been fully evaluated (usually at the ';' at the end of the
statement).
26

4.8 Dynamic storage duration objects


These objects have a dynamic lifespan and are created with new call and destroyed with an explicit
call to delete.
4.8.1 Objects
C++ introduces object-oriented programming (OOP) features to C. It offers classes, which provide
the four features commonly present in OOP (and some non-OOP) languages: abstraction,
encapsulation, inheritance, and polymorphism. One distinguishing feature of C++ classes
compared to classes in other programming languages is support for deterministic destructors,
which in turn provide support for the Resource Acquisition is Initialization (RAII) concept.
4.8.2 Encapsulation
Encapsulation is the hiding of information to ensure that data structures and operators are used as
intended and to make the usage model more obvious to the developer. C++ provides the ability to
define classes and functions as its primary encapsulation mechanisms. Within a class, members can
be declared as either public, protected, or private to explicitly enforce encapsulation. A public
member of the class is accessible to any function. A private member is accessible only to functions
that are members of that class and to functions and classes explicitly granted access permission by
the class ("friends"). A protected member is accessible to members of classes that inherit from the
class in addition to the class itself and any friends.
The OO principle is that all of the functions (and only the functions) that access the internal
representation of a type should be encapsulated within the type definition. C++ supports this (via
member functions and friend functions), but does not enforce it: the programmer can declare parts
or all of the representation of a type to be public, and is allowed to make public entities that are not
part of the representation of the type. Therefore, C++ supports not just OO programming, but other
weaker decomposition paradigms, like modular programming.
It is generally considered good practice to make all data private or protected, and to make public
only those functions that are part of a minimal interface for users of the class. This can hide the
details of data implementation, allowing the designer to later fundamentally change the
implementation without changing the interface in any way.
4.8.3 Inheritance
27

Inheritance allows one data type to acquire properties of other data types. Inheritance from a base
class may be declared as public, protected, or private. This access specifier determines whether
unrelated and derived classes can access the inherited public and protected members of the base
class. Only public inheritance corresponds to what is usually meant by "inheritance". The other two
forms are much less frequently used. If the access specifier is omitted, a "class" inherits privately,
while a "struct" inherits publicly. Base classes may be declared as virtual; this is called virtual
inheritance. Virtual inheritance ensures that only one instance of a base class exists in the
inheritance graph, avoiding some of the ambiguity problems of multiple inheritance.
Multiple inheritance is a C++ feature not found in most other languages, allowing a class to be
derived from more than one base class; this allows for more elaborate inheritance relationships. For
example, a "Flying Cat" class can inherit from both "Cat" and "Flying Mammal". Some other
languages, such as C# or Java, accomplish something similar (although more limited) by allowing
inheritance of multiple interfaces while restricting the number of base classes to one (interfaces,
unlike classes, provide only declarations of member functions, no implementation or member
data). An interface as in C# and Java can be defined in C++ as a class containing only pure virtual
functions, often known as an abstract base class or "ABC". The member functions of such an
abstract base class are normally explicitly defined in the derived class, not inherited implicitly. C++
virtual inheritance exhibits an ambiguity resolution feature called dominance.
4.8.4 Polymorphism
Polymorphism enables one common interface for many implementations, and for objects to act
differently under different circumstances.
C++ supports several kinds of static (compile-time) and dynamic (run-time) polymorphisms.
Compile-time polymorphism does not allow for certain run-time decisions, while run-time
polymorphism typically incurs a performance penalty.
Static polymorphism
Function overloading allows programs to declare multiple functions having the same name (but
with different arguments). The functions are distinguished by the number or types of their formal
parameters. Thus, the same function name can refer to different functions depending on the context
in which it is used. The type returned by the function is not used to distinguish overloaded
functions and would result in a compile-time error message.
28

When declaring a function, a programmer can specify for one or more parameters a default value.
Doing so allows the parameters with defaults to optionally be omitted when the function is called,
in which case the default arguments will be used. When a function is called with fewer arguments
than there are declared parameters, explicit arguments are matched to parameters in left-to-right
order, with any unmatched parameters at the end of the parameter list being assigned their default
arguments. In many cases, specifying default arguments in a single function declaration is
preferable to providing overloaded function definitions with different numbers of parameters.
Templates in C++ provide a sophisticated mechanism for writing generic, polymorphic code. In
particular, through the Curiously Recurring Template Pattern, it's possible to implement a form of
static polymorphism that closely mimics the syntax for overriding virtual functions. Because C++
templates are type-aware and Turing-complete, they can also be used to let the compiler resolve
recursive conditionals and generate substantial programs through template metaprogramming.
Contrary to some opinion, template code will not generate a bulk code after compilation with the
proper compiler settings.
Dynamic polymorphism
Inheritance
Variable pointers (and references) to a base class type in C++ can refer to objects of any derived
classes of that type in addition to objects exactly matching the variable type. This allows arrays and
other kinds of containers to hold pointers to objects of differing types. Because assignment of
values to variables usually occurs at run-time, this is necessarily a run-time phenomenon.
C++ also provides a dynamic_cast operator, which allows the program to safely attempt conversion
of an object into an object of a more specific object type (as opposed to conversion to a more
general type, which is always allowed). This feature relies on run-time type information (RTTI).
Objects known to be of a certain specific type can also be cast to that type with static_cast, a purely
compile-time construct that has no runtime overhead and does not require RTTI.
4.8.5 Virtual member functions
Ordinarily, when a function in a derived class overrides a function in a base class, the function to
call is determined by the type of the object. A given function is overridden when there exists no
difference in the number or type of parameters between two or more definitions of that function.
Hence, at compile time, it may not be possible to determine the type of the object and therefore the
correct function to call, given only a base class pointer; the decision is therefore put off until
29

runtime. This is called dynamic dispatch. Virtual member functions or methods allow the most
specific implementation of the function to be called, according to the actual run-time type of the
object. In C++ implementations, this is commonly done using virtual function tables. If the object
type is known, this may be bypassed by prepending a fully qualified class name before the function
call, but in general calls to virtual functions are resolved at run time.
In addition to standard member functions, operator overloads and destructors can be virtual. A
general rule of thumb is that if any functions in the class are virtual, the destructor should be as
well. As the type of an object at its creation is known at compile time, constructors, and by
extension copy constructors, cannot be virtual. Nonetheless a situation may arise where a copy of
an object needs to be created when a pointer to a derived object is passed as a pointer to a base
object. In such a case, a common solution is to create a clone() (or similar) virtual function that
creates and returns a copy of the derived class when called.
A member function can also be made "pure virtual" by appending it with = 0 after the closing
parenthesis and before the semicolon. A class containing a pure virtual function is called an
abstract data type. Objects cannot be created from abstract data types; they can only be derived
from. Any derived class inherits the virtual function as pure and must provide a non-pure definition
of it (and all other pure virtual functions) before objects of the derived class can be created. A
program that attempts to create an object of a class with a pure virtual member function or
inherited pure virtual member function is ill-formed.
4.9 THREADING
Multithreading is a specialized form of multitasking and a multitasking is the feature that allows
your computer to run two or more programs concurrently. In general, there are two types of
multitasking: process-based and thread-based.
Process-based multitasking handles the concurrent execution of programs. Thread-based
multitasking deals with the concurrent execution of pieces of the same program.
A multithreaded program contains two or more parts that can run concurrently. Each part of such a
program is called a thread, and each thread defines a separate path of execution.
C++ does not contain any built-in support for multithreaded applications. Instead, it relies entirely
upon the operating system to provide this feature.

30

This tutorial assumes that you are working on Linux OS and we are going to write multi-threaded
C++ program using POSIX. POSIX Threads, or Pthreads provides API which are available on
many Unix-like POSIX systems such as FreeBSD, NetBSD, GNU/Linux, Mac OS X and Solaris.

31

5. Observer Design Pattern

5.1 Intent

Define a one-to-many dependency between objects so that when one object changes state,
all its dependents are notified and updated automatically.

Encapsulate the core (or common or engine) components in a Subject abstraction, and the
variable (or optional or user interface) components in an Observer hierarchy.

The "View" part of Model-View-Controller.

5.2 Problem
A large monolithic design does not scale well as new graphing or monitoring requirements are
levied.

5.3 Discussion
Define an object that is the "keeper" of the data model and/or business logic (the Subject). Delegate
all "view" functionality to decoupled and distinct Observer objects. Observers register themselves
with the Subject as they are created. Whenever the Subject changes, it broadcasts to all registered
Observers that it has changed, and each Observer queries the Subject for that subset of the
Subject's state that it is responsible for monitoring.
This allows the number and "type" of "view" objects to be configured dynamically, instead of
being statically specified at compile-time.
The protocol described above specifies a "pull" interaction model. Instead of the Subject "pushing"
what has changed to all Observers, each Observer is responsible for "pulling" its particular
"window of interest" from the Subject. The "push" model compromises reuse, while the "pull"
model is less efficient.
Issues that are discussed, but left to the discretion of the designer, include: implementing event
compression (only sending a single change broadcast after a series of consecutive changes has
occurred), having a single Observer monitoring multiple Subjects, and ensuring that a Subject
notify its Observers when it is about to go away.
32

The Observer pattern captures the lion's share of the Model-View-Controller architecture that has
been a part of the Smalltalk community for years.

5.4 Structure

Subject represents the core (or independent or common or engine) abstraction. Observer represents
the variable (or dependent or optional or user interface) abstraction. The Subject prompts the
Observer objects to do their thing. Each Observer can call back to the Subject as needed.

Example
The Observer defines a one-to-many relationship so that when one object changes state, the others
are notified and updated automatically. Some auctions demonstrate this pattern. Each bidder
possesses a numbered paddle that is used to indicate a bid. The auctioneer starts the bidding, and
"observes" when a paddle is raised to accept the bid. The acceptance of the bid changes the bid
price which is broadcast to all of the bidders in the form of a new bid.

33

5.5 Check list


1.

Differentiate between the core (or independent) functionality and the optional (or
dependent) functionality.

2.

Model the independent functionality with a "subject" abstraction.

3.

Model the dependent functionality with an "observer" hierarchy.

4.

The Subject is coupled only to the Observer base class.

5.

The client configures the number and type of Observers.

6.

Observers register themselves with the Subject.

7.

The Subject broadcasts events to all registered Observers.

8.

The Subject may "push" information at the Observers, or, the Observers may "pull" the
information they need from the Subject.

34

5.6 Rules of thumb

Chain of Responsibility, Command, Mediator, and Observer, address how you can decouple
senders and receivers, but with different trade-offs. Chain of Responsibility passes a sender request
along a chain of potential receivers. Command normally specifies a sender-receiver connection
with a subclass. Mediator has senders and receivers reference each other indirectly. Observer
defines a much decoupled interface that allows for multiple receivers to be configured at run-time.

Mediator and Observer are competing patterns. The difference between them is that
Observer distributes communication by introducing "observer" and "subject" objects, whereas a
Mediator object encapsulates the communication between other objects. We've found it easier to
make reusable Observers and Subjects than to make reusable Mediators.

On the other hand, Mediator can leverage Observer for dynamically registering colleagues
and communicating with them.

5.7 Observer design pattern


1.

Model the "independent" functionality with a "subject" abstraction

2.

Model the "dependent" functionality with "observer" hierarchy

3.

The Subject is coupled only to the Observer base class

4.

Observers register themselves with the Subject

5.

The Subject broadcasts events to all registered Observers

6.

Observers "pull" the information they need from the Subject

7.

Client configures the number and type of Observers


#include <iostream>
#include <vector>
using namespace std;
class Subject {
// 1. "independent" functionality
vector < class Observer * > views; // 3. Coupled only to "interface"
int value;
public:
void attach(Observer *obs) {
views.push_back(obs);
}

35

void setVal(int val) {


value = val;
notify();
}
int getVal() {
return value;
}
void notify();
};
class Observer {
// 2. "dependent" functionality
Subject *model;
int denom;
public:
Observer(Subject *mod, int div) {
model = mod;
denom = div;
// 4. Observers register themselves with the Subject
model->attach(this);
}
virtual void update() = 0;
protected:
Subject *getSubject() {
return model;
}
int getDivisor() {
return denom;
}
};
void Subject::notify() {
// 5. Publisher broadcasts
for (int i = 0; i < views.size(); i++)
views[i]->update();
}
class DivObserver: public Observer {
public:
DivObserver(Subject *mod, int div): Observer(mod, div){}
void update() {
// 6. "Pull" information of interest
int v = getSubject()->getVal(), d = getDivisor();
cout << v << " div " << d << " is " << v / d << '\n';
}
};
class ModObserver: public Observer {

36

public:
ModObserver(Subject *mod, int div): Observer(mod, div){}
void update() {
int v = getSubject()->getVal(), d = getDivisor();
cout << v << " mod " << d << " is " << v % d << '\n';
}
};
int main() {
Subject subj;
DivObserver divObs1(&subj, 4); // 7. Client configures the number and
DivObserver divObs2(&subj, 3); // type of Observers
ModObserver modObs3(&subj, 3);
subj.setVal(14);
}

1.1.1.1 Output
14 div 4 is 3
14 div 3 is 4
14 mod 3 is 2

37

5.8 Observer Pattern


Observer Pattern's intent is to define a one-to-many dependency between objects so that when
one object changes state, all its dependents are notified and updated automatically.

38

39

WITHOUT P-THREADS

40

The subject and observers define the one-to-many relationship. The observers are dependent on
the subject such that when the subject's state changes, the observers get notified. Depending on the
notification, the observers may also be updated with new values.

#include <iostream>
#include
#include
#include
#include
#include

<vector>
<time.h>
<sys/types.h>
<sys/timeb.h>
<string.h>

using namespace std ;


class Subject;
class Observer
{
41

public:
Observer() {};
~Observer() {};
virtual void Update(Subject* theChangeSubject) = 0;
};
class Subject
{
public:
Subject() {};
virtual ~Subject() {};
virtual void Attach(Observer*);
virtual void Detach(Observer*);
virtual void Notify();
private:
vector<Observer*> _observers;
};
void Subject::Attach (Observer* o)
{
_observers.push_back(o);
}
void Subject::Detach (Observer* o)
{
int count = _observers.size();
int i;
for (i = 0; i < count; i++) {
if(_observers[i] == o)
break;
}
if(i < count)
_observers.erase(_observers.begin() + i);
}
void Subject::Notify ()
{
int count = _observers.size();
for (int i = 0; i < count; i++)
(_observers[i])->Update(this);
}
class ClockTimer : public Subject
{
public:
ClockTimer() { _strtime( tmpbuf ); };
int GetHour();
int GetMinute();
42

int GetSecond();
void Tick();
private:
char tmpbuf[128];
};
/* Set time zone from TZ environment variable. If TZ is not set,
* the operating system is queried to obtain the default value
* for the variable.
*/
void ClockTimer::Tick()
{
_tzset();
// Obtain operating system-style time.
_strtime( tmpbuf );
Notify();
}
int ClockTimer::GetHour()
{
char timebuf[128];
strncpy(timebuf, tmpbuf, 2);
timebuf[2] = NULL;
return atoi(timebuf);
}
int ClockTimer::GetMinute()
{
char timebuf[128];
strncpy(timebuf, tmpbuf+3, 2);
timebuf[2] = NULL;
return atoi(timebuf);
}
int ClockTimer::GetSecond()
{
char timebuf[128];
strncpy(timebuf, tmpbuf+6, 2);
timebuf[2] = NULL;
return atoi(timebuf);
}
class DigitalClock: public Observer
{
public:
DigitalClock(ClockTimer *);
43

~DigitalClock();
void Update(Subject *);
void Draw();
private:
ClockTimer *_subject;
};
DigitalClock::DigitalClock (ClockTimer *s)
{
_subject = s;
_subject->Attach(this);
}
DigitalClock::~DigitalClock ()
{
_subject->Detach(this);
}
void DigitalClock::Update (Subject *theChangedSubject)
{
if(theChangedSubject == _subject)
Draw();
}
void DigitalClock::Draw ()
{
int hour = _subject->GetHour();
int minute = _subject->GetMinute();
int second = _subject->GetSecond();
cout << "Digital time is " << hour << ":"
<< minute << ":"
<< second << endl;
}
class AnalogClock: public Observer
{
public:
AnalogClock(ClockTimer *);
~AnalogClock();
void Update(Subject *);
void Draw();
private:
ClockTimer *_subject;
};
AnalogClock::AnalogClock (ClockTimer *s)
{
_subject = s;
_subject->Attach(this);
}
44

AnalogClock::~AnalogClock ()
{
_subject->Detach(this);
}
void AnalogClock::Update (Subject *theChangedSubject)
{
if(theChangedSubject == _subject)
Draw();
}
void AnalogClock::Draw ()
{
int hour = _subject->GetHour();
int minute = _subject->GetMinute();
int second = _subject->GetSecond();
cout << "Analog time is " << hour << ":"
<< minute << ":"
<< second << endl;
}
int main(void)
{
ClockTimer timer;
DigitalClock digitalClock(&timer);
AnalogClock analogClock(&timer);
timer.Tick();
return 0;
}
Output:
Digital time is 14:41:36
Analog time is 14:41:36
Here are the summary of the pattern:
Objects (DigitalClock or AnalogClock object) use the Subject interfaces (Attach() or
Detach()) either to subscribe (register) as observers or unsubscribe (remove)
themselves from being observers.
DigitalClock::DigitalClock (ClockTimer *s)
{
_subject = s;
_subject->Attach(this);
}
45

DigitalClock::~DigitalClock ()
{
_subject->Detach(this);
}
Each subject can have many observers.
class Subject
{
public:
Subject() {};
~Subject() {};
void Attach(Observer*);
void Detach(Observer*);
void Notify();
private:
vector<Observer*> _observers;
};
All observers need to implement the Observer interface. This interface just has one
method, Update(), that gets called when the Subject's state changes.
class AnalogClock: public Observer
{
public:
AnalogClock(ClockTimer *);
~AnalogClock();
void Update(Subject *);
void Draw();
private:
ClockTimer *_subject;
};
In addition to the attach() and detach() methods, the concrete subject implements a
Notify() method that is used to update all the current observers whenever state
changes. But in this case, all of them are done in the parent class, Subject.
void Subject::Attach (Observer* o)
{
_observers.push_back(o);
}
void Subject::Detach(Observer* o)
{
int count = _observers.size();
int i;
for (i = 0; i < count; i++) {
if(_observers[i] == o)
break;
}
if(i < count)
_observers.erase(_observers.begin() + i);
}
46

void Subject::Notify()
{
int count = _observers.size();
for (int i = 0; i < count; i++)
(_observers[i])->Update(this);
}
The Concrete object may also have methods for setting and getting its state.
class ClockTimer : public Subject
{
public:
ClockTimer() { _strtime( tmpbuf ); };
int GetHour();
int GetMinute();
int GetSecond();
void Tick();
private:
char tmpbuf[128];
};
Concrete observers can be any class that implements the Observer interface. Each
observer subscribe (register) with a concrete subject to receive update.
DigitalClock::DigitalClock (ClockTimer *s)
{
_subject = s;
_subject->Attach(this);
}
The two objects of Observer Pattern are loosely coupled, they can interact but with
little knowledge of each other.

2nd Example of Observer Pattern


The following example is not much different from the previous one. The important point to notice
is that the MySubject class has not compile-time dependency on theMyObserver class. The
relationship between the two classes is dynamically created at run time.
#include <iostream>
#include <vector>
#include <string>
class ObserverInterface
{
public:
virtual ~ObserverInterface() {}
virtual void update(int message) = 0;
};
47

class SubjectInterface
{
public:
virtual ~SubjectInterface();
virtual void subscribe(ObserverInterface *);
virtual void unsubscribe (ObserverInterface *);
virtual void notify(int message);
private:
std::vector<ObserverInterface *> mObservers;
};
SubjectInterface::~SubjectInterface()
{}
void SubjectInterface::subscribe(ObserverInterface *observer)
{
mObservers.push_back(observer);
}
void SubjectInterface::unsubscribe(ObserverInterface *observer)
{
int count = mObservers.size();
int i;
for (i = 0; i < count; i++) {
if(mObservers[i] == 0)
break;
}
if(i < count)
mObservers.erase(mObservers.begin() + i);
}
void SubjectInterface::notify(int msg)
{
int count = mObservers.size();
for (int i = 0; i < count; i++)
(mObservers[i])->update(msg);
}
class MySubject : public SubjectInterface
{
public:
enum Message {ADD, REMOVE};
};
class MyObserver : public ObserverInterface
{
public:
explicit MyObserver(const std::string &str) : name(str) {}
void update(int message)
48

{
std::cout << name << " Got message " << message << std::endl;
}
private:
std::string name;
};
int main()
{
MyObserver observerA("observerA");
MyObserver observerB("observerB");
MyObserver observerC("observerC");
MySubject subject;
subject.subscribe(&observerA);
subject.subscribe(&observerB);
subject.unsubscribe(&observerB);
subject.subscribe(&observerC);
subject.notify(MySubject::ADD);
subject.notify(MySubject::REMOVE);
return 0;
}
Output:
observerA
observerB
observerC
observerA
observerB
observerC

Got
Got
Got
Got
Got
Got

message
message
message
message
message
message

0
0
0
1
1
1

The calls to subject.notify() cause the subject to traverse its list of observers that have been
subscribed and the call to (mObservers[i])->update(msg) method for each of them.
There may be a small performance hit due to iterating through a list of observers before making the
virtual function call. However, the cost is minimal when compared to the benefits of reduced
coupling and increased code reuse.

5.9 Variations
49

There are some variation of the Observer pattern.

Signal and Slots


Signals and slots is a language construct introduced in Qt, which makes it easy to
implement the Observer pattern while avoiding boilerplate code. The concept is
that controls (also known as widgets) can send signals containing event
information which can be received by other controls using special functions known
as slots. The slot in Qt must be a class member declared as such.
The signal/slot system fits well with the way Graphical User Interfaces are designed.
Similarly, the signal/slot system can be used for asynchronous I/O (including sockets,
pipes, serial devices, etc.) event notification or to associate timeout events with appropriate
object instances and methods or functions. No registration/deregistration/invocation code
need be written, because Qt's Meta Object Compiler (MOC) automatically generates the
needed infrastructure.

C# Events and Delegates


The C# language also supports a similar construct although with a different terminology
and syntax: events play the role of signals, and delegates are theslots. Additionally,
a delegate can be a local variable, much like a function pointer, while a slot in Qt must be a
class member declared as such.

6. N-ARY TREE
A N-ary tree is a rooted tree in which each node has no more than k children. It is also sometimes
known as a k-way tree, an N-ary tree, or an M-ary tree. A binary tree is the special case where k=2.
According to Definition, an N-ary tree is either the empty tree, or it is a non-empty set of nodes
which consists of a root and exactly N sub trees. Clearly, the empty set contains neither a root, nor
any sub trees. Therefore, the degree of each node of an N-ary tree is either zero or N.
Considering a Sample N-ary tree
R

/|\
BCD

|
->

B -- C -- D
50

/\ |

E FG

E -- F

|
G

Basically, where the root points only to the first children, if the roots have more children (subnodes), they would be pointed by other children. (Head is first child of the father)
6.1 TYPES OF N-ARY TREE :

A full k-ary tree is a k-ary tree where within each level every node has
either 0 or k children.

A perfect k-ary tree is a full k-ary tree in which all leaf nodes are at the same depth.

A complete k-ary tree is a k-ary tree which is maximally space efficient. It must be
completely filled on every level (meaning that each node on that level has k children)
except for the last level. However, if the last level is not complete, then all nodes of the tree
must be "as far left as possible".

51

6.2 STRUCTURE OF AN N-ARY TREE

52

Algorithm for the fastest way to search for node in the tree along with its insertion

53

For In-Case N-ary tree represented in Binary Tree. We follow the algorithm:

54

6.3 ALGORITHM FOR DELETION OF A NODE

55

7. CONCLUSION
Software development has his own boons and cons. In todays fast paced generation coding can
render a multi-national company with the following benefits and scopes of sorts: IT management & security

Business process management (BPM)

Enterprise resource planning (ERP)

Supply chain management (SCM)

Decision support systems (DSS)

Customer relationship management (CRM)

Collaboration software

Productivity software My domain

56

8. BIBLIOGRAPHY

https://www.globallogic.com/
C++ Buckys modules 1,2 and 3
www.code.org
http://www.bogotobogo.com/DesignPatterns/observer.php
Learn C++ by Sumita Arora volume 2013

57

Das könnte Ihnen auch gefallen