3) Comparison of Java and C++

advertisement
OBJECT ORIENTED PROGRAMMING
GROUP-A
5MARKS:
1) Object-oriented programming
Object-oriented programming (OOP) is a programming paradigm using "objects" – data
structures consisting ofdata fields and methods together with their interactions – to design
applications and computer programs. Programming techniques may include features such asdata
abstraction, encapsulation, messaging, modularity,polymorphism, and inheritance. Many
modernprogramming languages now support OOP, at least as an option.
In contrast, the object-oriented approach encourages the programmer to place data where it is not
directly accessible by the rest of the program. Instead, the data is accessed by calling specially
written functions, commonly called methods, which are either bundled in with the data or
inherited from "class objects." These act as the intermediaries for retrieving or modifying the
data they control. The programming construct that combines data with a set of methods for
accessing and managing those data is called an object. The practice of using subroutines to
examine or modify certain kinds of data was also used in non-OOP modular programming, well
before the widespread use of object-oriented programming.
An object-oriented program will usually contain different types of objects, each type
corresponding to a particular kind of complex data to be managed or perhaps to a real-world
object or concept such as a bank account, a hockey player, or a bulldozer. A program might well
contain multiple copies of each type of object, one for each of the real-world objects the program
is dealing with. For instance, there could be one bank account object for each real-world account
at a particular bank. Each copy of the bank account object would be alike in the methods it offers
for manipulating or reading its data, but the data inside each object would differ reflecting the
different history of each account.
Objects can be thought of as wrapping their data within a set of functions designed to ensure that
the data are used appropriately, and to assist in that use. The object's methods will typically
include checks and safeguards that are specific to the types of data the object contains. An object
can also offer simple-to-use, standardized methods for performing particular operations on its
data, while concealing the specifics of how those tasks are accomplished. In this way alterations
can be made to the internal structure or methods of an object without requiring that the rest of the
program be modified. This approach can also be used to offer standardized methods across
different types of objects. As an example, several different types of objects might offer print
methods. Each type of object might implement that print method in a different way, reflecting
the different kinds of data each contains, but all the different print methods might be called in the
same standardized manner from elsewhere in the program. These features become especially
useful when more than one programmer is contributing code to a project or when the goal is to
reuse code between projects.
Object-oriented programming has roots that can be traced to the 1960s. As hardware and
software became increasingly complex, manageability often became a concern. Researchers
studied ways to maintain software quality and developed object-oriented programming in part to
address common problems by strongly emphasizing discrete, reusable units of programming
logic[citation needed]. The technology focuses on data rather than processes, with programs composed
of self-sufficient modules ("classes"), each instance of which ("objects") contains all the
information needed to manipulate its own data structure ("members"). This is in contrast to the
existing modular programming that had been dominant for many years that focused on
the function of a module, rather than specifically the data, but equally provided for code reuse,
and self-sufficient reusable units of programming logic, enabling collaboration through the use
of linked modules (subroutines).
2) OOP languages
Simula (1967) is generally accepted as the first language to have the primary features of an
object-oriented language. It was created for making simulation programs, in which what came to
be called objects were the most important information representation. Smalltalk (1972 to 1980) is
arguably the canonical example, and the one with which much of the theory of object-oriented
programming was developed. Concerning the degree of object orientation, the following
distinctions can be made:

Languages called "pure" OO languages, because everything in them is treated
consistently as an object, from primitives such as characters and punctuation, all the way up
to whole classes, prototypes, blocks, modules, etc. They were designed specifically to
facilitate, even enforce, OO methods.
Examples: Eiffel, Emerald.[19], JADE, Obix, Scala, Smalltalk

Languages designed mainly for OO programming, but with some procedural elements.
Examples:C++, Java, C#, VB.NET, Python.

Languages that are historically procedural languages, but have been extended with some
OO features. Examples: Visual Basic (derived from
BASIC), Fortran, Perl, COBOL 2002, PHP, ABAP.

Languages with most of the features of objects (classes, methods, inheritance,
reusability), but in a distinctly original form. Examples: Oberon (Oberon-1 or Oberon-2)
and Common Lisp.

Languages with abstract data type support, but not all features of object-orientation,
sometimes called object-based languages. Examples: Modula-2 (with excellent encapsulation
and information hiding), Pliant, CLU.
OOP in dynamic languages
In recent years, object-oriented programming has become especially popular in dynamic
programming languages. Python, Ruby and Groovy are dynamic languages built on OOP
principles, while Perl andPHP have been adding object oriented features since Perl 5 and PHP 4,
and ColdFusion since version 5.
The Document Object Model of HTML, XHTML, and XML documents on the Internet have
bindings to the popular JavaScript/ECMAScript language. JavaScript is perhaps the best
known prototype-based programming language, which employs cloning from prototypes rather
than inheriting from a class. Another scripting language that takes this approach is Lua. Earlier
versions of ActionScript (a partial superset of the ECMA-262 R3, otherwise known as
ECMAScript) also used a prototype-based object model. Later versions of ActionScript
incorporate a combination of classification and prototype-based object models based largely on
the currently incomplete ECMA-262 R4 specification, which has its roots in an early JavaScript
2 Proposal. Microsoft's JScript.NET also includes a mash-up of object models based on the same
proposal, and is also a superset of the ECMA-262 R3 specification.
3)
#include <conio.h>
#include <graphics.h>
#include <stdlib.h>
#include <stdio.h>
void main (int)
{
int gdriver=DETECT,gmode,errorcode; //Requesting auto-detection.
int midx,midy,x;
//Initializing graphics and local variables.
initgraph(&gdriver,&gmode,"d:\\bc3\\bgi");
//Reading result of initialization.
errorcode=graphresult();
if(errorcode!=grOk)
//An error occurred.
{
printf("Graphics error occurred : %s \n",grapherrormsg(errorcode));
printf("Press any key to stop : ");
getch();
exit(1); //Terminate the program due to error.
}
for(x=40;x<120;x=x+10)
{
putpixel(x,200,14); //Plots 1 pixel at position(x,200) with YELLOW color(14)
getch();
}
}
GROUP-B
20MARKS:
1) Language features
C++ inherits most of C's syntax. The following is Bjarne Stroustrup's version of the Hello world
programthat uses the C++ Standard Library stream facility to write a message to standard
output:[23][24]
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 behaviour (compilers typically provide the
means to issue a diagnostic in such a case).[25] The sole exception to this rule is
the main function, which implicitly returns a value of zero.[26]
Operators and operator overloading
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 using C++ as a domainspecific language. The 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.
Operators that cannot be overloaded
Operator
Symbol
Scope resolution operator
::
Conditional operator
?:
Member selection operator
.*
"sizeof" operator
sizeof
"typeid" operator
typeid
Templates
C++ templates enable generic programming. C++ supports both function and class templates.
Templates may be parameterized by types, compile-time constants, and other templates. C++
templates are implemented by instantiation at compile-time. To instantiate a template, compilers
substitute specific arguments for a template's parameters to generate a concrete function or class
instance. Some substitutions are not possible; these are eliminated by an overload resolution
policy described by the phrase "Substitution failure is not an error" (SFINAE). Templates are a
powerful tool that can be used for generic programming, template metaprogramming, and code
optimization, but this power implies a cost. Template use may increase code size, since each
template instantiation produces a copy of the template code: one for each set of template
arguments. This is in contrast to run-time generics seen in other languages (e.g. Java) where at
compile-time the type is erased and a single template body is preserved.
Templates are different from macros: while both of these compile-time language features enable
conditional compilation, templates are not restricted to lexical substitution. Templates are aware
of the semantics and type system of their companion language, as well as all compile-time type
definitions, and can perform high-level operations including programmatic flow control based on
evaluation of strictly type-checked parameters. Macros are capable of conditional control over
compilation based on predetermined criteria, but cannot instantiate new types, recurse, or
perform type evaluation and in effect are limited to pre-compilation text-substitution and textinclusion/exclusion. In other words, macros can control compilation flow based on pre-defined
symbols but cannot, unlike templates, independently instantiate new symbols. Templates are a
tool for static polymorphism (see below) andgeneric programming.
In addition, templates are a compile time mechanism in C++ that is Turing-complete, meaning
that any computation expressible by a computer program can be computed, in some form, by
a template metaprogram prior to runtime.
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. Objects are instances of
classes created at runtime. 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 Initializationconcept.
Encapsulation
Encapsulation is the hiding of information in order 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 in order 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.
Inheritance
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.
2) 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.
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. Since
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.[29]
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 is faster and does not require RTTI.
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
runtime. This is called dynamic dispatch. Virtual member functions or methods[30] 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.
Parsing (in the literal sense of producing a syntax tree) is not the most difficult problem in
building a C++ processing tool. Such tools must also have the same understanding of the
meaning of the identifiers in the program as a compiler might have. Practical systems for
processing C++ must then not only parse the source text, but be able to resolve for each identifier
precisely which definition applies (e.g. they must correctly handle C++'s complex scoping rules)
and what its type is, as well as the types of larger expressions.
Finally, a practical C++ processing tool must be able to handle the variety of C++ dialects used
in practice (such as that supported by the GNU Compiler Collection and that of
Microsoft's Visual C++) and implement appropriate analyzers, source code transformers, and
regenerate source text. Combining advanced parsing algorithms such as GLR with symbol
table construction and program transformation machinery can enable the construction of
arbitrary C++ tools.
3) Comparison of Java and C++
The different goals in the development of C++ and Java resulted in different principles and
design trade-offs between the languages. The differences are as follows :
C++
Java
Compatible with C source code, except for a
fewcorner cases.
No backward compatibility with any previous
language. The syntax is, however, strongly
influenced by C/C++.
Write once, compile anywhere (WOCA).
Write once, run anywhere / everywhere (WORA /
WORE).
Allows procedural programming, functional
programming, object-oriented programming,
andtemplate metaprogramming.
Strongly encourages an objectorientedprogramming paradigm.
Allows direct calls to native system libraries.
Call through the Java Native Interface and
recently Java Native Access
Exposes low-level system facilities.
Runs in a virtual machine. Does not always
provide full access to the features and
performance of the platform on which the
software runs.
Only provides object types and type names.
Is reflective, allowing metaprogramming and
dynamic code generation at runtime.
Has multiple binary compatibility standards
(commonly Microsoft and Itanium/GNU).
Has a binary compatibility standard, allowing
runtime check of correctness of libraries.
Optional automated bounds checking (e.g.,
Normally performs bounds checking. HotSpotcan
theat() method in vector and stringcontainers). remove bounds checking.
Supports native unsigned arithmetic.
No native support for unsigned arithmetic.
Standardized minimum limits for all
numerical types, but the actual sizes are
implementation-defined. Standardized types
are available as typedefs (uint8_t, ...,
uintptr_t, ...).
Standardized limits and sizes of all primitive
types on all platforms.
Pointers, references, and pass-by-value are
supported.
Primitive and reference data types always passed
by value.[1]
Explicit memory management. Supports
destructors. C++11 replaces the old standard
RAII auto_ptr<T> by unique_ptr<T> and
adds shared_ptr<T> (smart pointer with
reference counter), though third party
frameworks exist to provide better garbage
collection.
Automatic garbage collection (can be triggered
manually). Doesn't have the concept ofdestructor,
and usage of finalize() is not recommended.
Only supports classes, and allocates them on
Supports classes, structs, and unions, and can
the heap. Java SE 6 optimizes with escape
allocate them on heap or stack.
analysis to allocate some objects on the stack.
Allows explicitly overriding types.
Rigid type safety except for widening
conversions. Autoboxing/unboxing added in Java
1.5.
The standard library has grown with each release.
The C++ Standard Library has a much more By version 1.6, the library included support for
limited scope and functionality than the Java locales, logging, containers and iterators,
standard library but includes language
algorithms, GUI programming (but not using the
support, diagnostics, general utilities, strings, system GUI), graphics, multi-threading,
locales, containers, algorithms, iterators,
networking, platform security, introspection,
numerics, input/output, and Standard C
dynamic class loading, blocking and nonLibrary. The Boost library offers more
blocking I/O. It provided interfaces or support
functionality, including threads and network classes for XML, XSLT, MIDI, database
I/O. Users must choose from a plethora of
connectivity, naming services (e.g. LDAP),
(mostly mutually incompatible) third-party
cryptography, security services (e.g. Kerberos),
libraries for GUI and other functionality.
print services, and web services. SWT offers an
abstraction for platform-specific GUIs.
Operator overloading for most operators.
The meaning of operators is generally immutable,
but the + and += operators have been overloaded
for Strings.
Full Multiple inheritance, including virtual
inheritance.
From classes, only single inheritance is allowed.
From Interfaces, Multiple inheritance is also
allowed.
Compile-time templates.
Generics are used to achieve an analogous effect
to C++ templates, but they do not translate from
source code to byte code due to the use of type
erasure by the compiler.
Function pointers, function objects, lambdas
(inC++11), and interfaces.
No function pointer mechanism. Instead, idioms
such as Interface, Adapter, and Listener are
extensively used.
No standard inline documentation
mechanism. Third-party software
Javadoc standard documentation.
(e.g. Doxygen) exists.
const keyword for defining immutable
variables and member functions that do not
change the object.
final provides a limited version of const,
equivalent to type* const pointers for objects and
plain const for primitive types only.
Noconst member functions, nor any equivalent
toconst type* pointers.
Supports the goto statement. ( Spaghetti
Programming)
Supports labels with loops and statement blocks.
Source code can be written to be platformindependent (can be compiled
for Windows,BSD, Linux, Mac OS
Compiled into byte code for the JVM. Byte code
X, Solaris, etc., without modification) and
is dependent on the Java platform, but is typically
written to take advantage of platform-specific independent of operating systemspecific features.
features. Typically compiled into native
machine code.
4)
#include <iostream.h>
#include <conio.h>
#include <graphics.h>
#include <ctype.h>
#include <stdlib.h>
#include <stdio.h>
void main()
{
clrscr();
int gd=DETECT,gm,errorcode; //Requesting auto-detection.
//Initializing graphics and local variables.
initgraph(&gd,&gm,"d:\\bc3\\bgi"); //Path where graphics drivers are installed
//Reading result of initialization.
errorcode=graphresult();
//An error occured.
if (errorcode!=grOk)
{
cout << "Graphics error occured : \n" << grapherrormsg(errorcode) << endl;
cout << "Press any key to stop : ";
getch();
exit(1);
}
circle(200,200,50); //Drawing a circle having center(200,200) and radius(50).
getch();
circle(300,203,40); //Drawing a circle having center(300,203) and radius(40).
getch();
circle(500,303,80); //Drawing a circle having center(500,303) and radius(80).
getch();
closegraph();
}
This graphics program draws three circles on the screen.
Download