Professional Documents
Culture Documents
Section –I Genesis
Data types are means to identify the type of data and associated operations of
handling it. C++ provides a predefined set of data types for handling the data it uses.
When variables are declared of a particular data type then the variable becomes the
place where the data is stored and data types is the type of value(data) stored by that
variable. Data can be of many types such as character, integer, real etc. since the data
to be dealt with are of many types, a programming language must provide different
data types. In C++ data types are of two types:-
Fundamental Data Types: As the name suggests these are the atomic or the
fundamental data types in C++. Earlier there was five of these (int, char, float, double
and void) but later two new data types namely bool and wchar_t have been added. Int
stores integer data or whole numbers such as 10, -340 etc., char stores any of the
ASCII characters, float is used to store numbers having fractional part such as 10.097,
double stores the same data as float but with higher range and precision, bool can only
store true and false values.
void main(void)
{
int age;
float salary;
char code;
cout<<"Enter age, salary and code:";
cin>>age;
cin>>salary;
cin>>code;
cout<<endl;//goto next line
cout<<"DETAILS"<<endl;//short for cout<<"DETAILS";cout<<endl;
cout<<"Age:"<<age<<endl;
cout<<"Salary:"<<salary<<endl; cout<<"Code:"<<code<<endl;
Preprocessor
directives
[iostream.h]
Source.code
“ somename.cpp”
Language C
Processor
[Compiler] Built-in fn
[Lib]
[Procedure
taken from
Linker]
somename.obj
Linker
L
somename.exe
get created
The Preprocessor
The Preprocessor accepts source code as input and is responsible for
• removing comments
• interpreting special preprocessor directives denoted by #.
For example
• #include -- includes contents of a named file. Files usually called header files.
e.g
o#include <math.h> -- standard library maths file.
o#include <stdio.h> -- standard library I/O file
• #define -- defines a symbolic name or constant. Macro substitution.
o #define MAX_ARRAY_SIZE 100
C Compiler
The C compiler translates source to assembly code. The source code is received from the
preprocessor.
Assembler
The assembler creates object code. On a UNIX system you may see files with a .o suffix (.OBJ on
MSDOS) to indicate object code files.
Link Editor
If a source file references library functions or functions defined in other source files the link editor
combines these functions (with main()) to create an executable file.
Encapsulation
Encapsulation is grouping data and functions together and keeping their
implementation details private. Greatly restricting access to functions and data reduces
coupling, which increases the ability to create large programs.
Classes also encourage coherence, which means that a given class does one thing. By
increasing coherence, a program becomes easier to understand, more simply
organized, and this better organization is reflected in a further reduction in coupling.
Inheritance
Inheritance means that a new class can be defined in terms of an existing class. There
are three common terminologies for the new class: the derived class, the child class, or
the subclass. The original class is the base class, the parent class, or the superclass.
The new child class inherits all capabilities of the parent class and adds its own fields
and methods. Altho inheritance is very important, especially in many libraries, is often
not used in an application.
Polymorphism
Polymorphism is the ability of different functions to be invoked with the same name.
There are two forms.
Static polymorphism is the common case of overriding a function by providing
additional definitions with different numbers or types of parameters. The compiler
matches the parameter list to the appropriate function.
Dynamic polymorphism is much different and relies on parent classes to define virtual
functions which child classes may redefine. When this virtual member function is called
for an object of the parent class, the execution dynamically chooses the appropriate
function to call - the parent function if the object really is the parent type, or the child
function if the object really is the child type. This explanation is too brief to be usesful
without an example, but that will have to be written latter.
method Same as function, but the typical OO notation is used for the call, ie,
f(x,y) is written x.f(y) where x is an object of class that contains this f
method.
send a
Call a function (method)
message
instantiate Allocate a class/struct object (ie, instance) with new
//overloading a constructor
public Example(int input)
{
data = input;
}
If no user-defined constructor exists for a class A and one is needed, the compiler
implicitly declares a constructor A::A(). This constructor is an inline public member
of its class. The compiler will implicitly define A::A() when the compiler uses this
constructor to create an object of type A. The constructor will have no constructor
initializer and a null body.
The compiler first implicitly defines the implicitly declared constructors of the base
classes and nonstatic data members of a class A before defining the implicitly
declared constructor of A. No default constructor is created for a class that has any
constant or reference type members
• Parameterized constructor
#include <iostream>
using namespace std;
class myclass
{
int a, b;
public:
myclass(int i, int j)
{
a=i;
b=j;
}
void show() {
cout << a << " " << b;
}
};
int main()
{
myclass ob(3, 5);
ob.show();
return 0;
}
• Copy-constructor
class myclass {
public:
string* [] a_pointer;
void newstring(void)
{
a_pointer[current++] = new string();
}
private:
int current;
};
Example
y = p.y;
}
. . .
//=== file my_program.cpp ====================================
. . .
Point p; // calls default constructor
Point s = p; // calls copy constructor.
p = s; // assignment, not copy constructor.
Categories of classes
There are many categories of classes depending on modifiers. Note that these
categories do not necessarily categorize classes into distinct partitions. For example,
while it is impossible to have a class that is both abstract and concrete, a sealed class
is implicitly a concrete class, and it may be possible to have an abstract partial class.
Concrete classes
A concrete class is a class that can be instantiated. This contrasts with abstract classes
as described below.
Abstract classes
An abstract class, or abstract base class (ABC), is a class that cannot be instantiated.
Such a class is only meaningful if the language supports inheritance. An abstract class
is designed only as a parent class from which child classes may be derived. Abstract
classes are often used to represent abstract concepts or entities. The incomplete
features of the abstract class are then shared by a group of subclasses which add
different variations of the missing pieces.
Abstract classes are superclasses which contain abstract methods and are defined such
that concrete subclasses are to extend them by implementing the methods. The
behaviors defined by such a class are "generic" and much of the class will be undefined
and unimplemented. Before a class derived from an abstract class can become
concrete, i.e. a class that can be instantiated, it must implement particular methods
for all the abstract methods of its parent classes.
When specifying an abstract class, the programmer is referring to a class which has
elements that are meant to be implemented by inheritance. The abstraction of the
class methods to be implemented by the subclasses is meant to simplify software
development. This also enables the programmer to focus on planning and design.
Most object oriented programming languages allow the programmer to specify which
classes are considered abstract and will not allow these to be instantiated.
Members of classes declared with the keyword class are private by default. Members of
classes declared with the keyword struct or union are public by default.
To control the access of a class member, you use one of the access specifiers public,
private, or protected as a label in a class member list. The following example
demonstrates these access specifiers:
class B : A {
{
// a = 1;
b = 2;
c = 3;
}
};
class C {
void f(A x) {
x.a = 4;
x.b = 5;
x.c = 6;
}
};
int main()
{
A y;
// y.a = 7;
y.b = 8;
// y.c = 9;
B z;
// z.a = 10;
z.b = 11;
// z.c = 12;
}
The following table lists the access of data members A::a A::b, and A::c in various
scopes of the above example.
object y in No access. Member y.a is Access. Member y.a is No access. Member y.c is
private. public. protected.
main()
An example of this would be a square function which takes a number and returns the
square of that number. In this case, it is often necessary to create different functions
for integer and floating point numbers.
For example, the class Person below, written in Java, holds data about each person's
name and phone number. The constructor is overloaded as there are two constructors
for the class Person.
The keyword this identifies a special type of pointer. Suppose that you create an object
named x of class A, and class A has a nonstatic member function f(). If you call the
function x.f(), the keyword this in the body of f() stores the address of x. You cannot
declare the this pointer or make assignments to it.
For example, you can refer to the particular class object that a member function is
called for by using the this pointer in the body of the member function. The following
code example produces the output a = 5:
#include <iostream>
using namespace std;
struct X {
private:
int a;
public:
void Set_a(int a) {
int main() {
X xobj;
int a = 5;
xobj.Set_a(a);
xobj.Print_a();
}
In the member function Set _a(), the statement this->a = a uses the this pointer to
retrieve xobj.a hidden by the automatic variable a.
The new classes, known as derived classes, take over (or inherit) attributes and
behavior of the pre-existing classes, which are referred to as base classes (or ancestor
classes). It is intended to help reuse existing code with little or no modification.
Inheritance provides the support for representation by categorization in computer
languages. Categorization is a powerful mechanism number of information processing,
crucial to human learning by means of generalization (what is known about specific
entities is applied to a wider group given a belongs relation can be established) and
cognitive economy (less information needs to be stored about each specific entity, only
its particularities).
Inheritance is also sometimes called generalization, because the is-a relationships
represent a hierarchy between classes of objects. For instance, a "fruit" is a
generalization of "apple", "orange", "mango" and many others. One can consider fruit
to be an abstraction of apple, orange, etc. Conversely, since apples are fruit (i.e., an
apple is-a fruit), apples may naturally inherit all the properties common to all fruit,
such as being a fleshy container for the seed of a plant.
Fruit
Base class
is a is a
Applications of inheritance
There are many different aspects to inheritance. Different uses focus on different
properties, such as the external behavior of objects, internal structure of the object,
structure of the inheritance hierarchy, or software engineering properties of
inheritance. Sometimes it's desirable to distinguish these uses, as it's not necessarily
obvious from context.
Specialization
One common reason to use inheritance is to create specializations of existing classes
or objects. This is often called subtyping when applied to classes. In specialization, the
new class or object has data or behavior aspects that are not part of the inherited
class. For example, a "Bank Account" class might have data for an "account number",
"owner", and "balance". An "Interest Bearing Account" class might inherit "Bank
Account" and then add data for "interest rate" and "interest accrued" along with
behavior for calculating interest earned.
Another form of specialization occurs when a base class specifies that it has a
particular behavior but does not actually implement the behavior. Each non-abstract,
concrete class which inherits from that abstract class must provide an implementation
of that behavior. This providing of actual behavior by a subclass is sometimes known
as implementation or reification.
Overriding
Code re-use
One of the earliest motivations for using inheritance was to allow a new class to re-use
code which already existed in another class. This practice is usually called
implementation inheritance.
In most quarters, class inheritance for the sole purpose of code re-use has fallen out of
favor. The primary concern is that implementation inheritance does not provide any
assurance of polymorphic substitutability—an instance of the re-using class cannot
necessarily be substituted for an instance of the inherited class. An alternative
technique, delegation, requires more programming effort but avoids the substitutability
issue. In C++ private inheritance can be used as form of implementation inheritance
without substitutability. Whereas public inheritance represents an "is-a" relationship
and delegation represents a "has-a" relationship, private (and protected) inheritance
can be thought of as an "is implemented in terms of relationship.
Object Oriented Software Construction, 2nd ed. by Bertrand Meyer, the creator of the
object-oriented programming language Eiffel, lists twelve different uses of inheritance,
most of which involve some amount of implementation inheritance.
In many cases, abstract classes are designed — i.e. classes that exist only in order to
have specialized subclasses derived from them. Such abstract classes have methods
that do not perform any useful operations and are meant to be overridden by specific
implementations in the subclasses. Thus, the abstract superclass defines a common
interface which all the subclasses inherit.
#include <iostream>
using namespace std;
class ThreeD {
int x, y, z;
public:
ThreeD() { x = y = z = 0; }
ThreeD(int i, int j, int k) {x = i; y = j; z = k; }
void show() ;
} ;
// Show X, Y, Z coordinates.
void ThreeD::show()
{
cout << x << ", ";
cout << y << ", ";
cout << z << "\n";
}
int main()
{
ThreeD a(1, 2, 3);
++a; // increment a
cout << "Value after ++a: ";
a.show();
return 0;
}
#include <iostream>
using namespace std;
class Point {
int x, y;
public:
Point() {} // needed to construct temporaries
Point(int px, int py) {
x = px;
y = py;
}
void show() {
cout << x << " ";
cout << y << "\n";
}
temp.x = op2.x + x;
temp.y = op2.y + y;
return temp;
}
return temp;
}
return *this;
}
int main()
{
Point ob1(10, 20), ob2( 5, 30), ob3(90, 90);
ob1.show();
ob2.show();
++ob1;
ob1.show(); // displays 11 21
ob2 = ++ob1;
ob1.show(); // displays 12 22
ob2.show(); // displays 12 22
return 0;
}
#include <iostream>
using namespace std;
class ThreeD {
int x, y, z;
public:
ThreeD() { x = y = z = 0; }
ThreeD(int i, int j, int k) { x = i; y = j; z = k; }
temp.x = x - op2.x;
temp.y = y - op2.y;
temp.z = z - op2.z;
return temp;
}
// Overload +.
ThreeD ThreeD::operator+(ThreeD op2)
{
ThreeD temp;
temp.x = x + op2.x;
temp.y = y + op2.x;
temp.z = z + op2.z;
return temp;
}
// Overload assignment.
ThreeD ThreeD::operator=(ThreeD op2)
{
x = op2.x;
y = op2.y;
z = op2.z;
return *this;
}
// Show X, Y, Z coordinates.
void ThreeD::show()
{
cout << x << ", ";
cout << y << ", ";
cout << z << "\n";
}
int main()
{
ThreeD a(1, 2, 3), b(10, 10, 10), c;
c = a - c;
cout << "a - c: ";
c.show();
return 0;
}
#include <iostream>
#include <cstdlib> // For random number generator
#include <ctime> // For time function
using std::cout;
using std::endl;
class Box {
public:
Box(double aLength, double aWidth, double aHeight):length(aLength), width(a
Width), height(aHeight) {}
private:
double length;
double width;
double height;
};
int main() {
return 0;
}
Polymorphism means to have one interface for different methods or functions. It is the
ability through which we can do different operations (by calling different functions)
from the same interface.
In OOP when a derived class inherits from a base class, an object of the derived class
may be referred to (or cast) as either being the base class type or the derived class
type. If there are base class functions overridden by the derived class, a problem then
arises when a derived object has been cast as the base class type. When a derived
object is referred to as being of the base's type, the desired function call behavior is
ambiguous.
The distinction between virtual and not virtual resolves this ambiguity. If the function
in question is designated "virtual" in the base class then the derived class's function
would be called (if it exists). If it is not virtual, the base class's function would be
called.
Virtual functions overcome the problems with the type-field solution by allowing the
programmer to declare functions in a base class that can be redefined in each derived
class.
A pure virtual function or pure virtual method is a virtual function that is required to be
implemented by a derived class that is not abstract. Classes containing pure virtual
methods are termed "abstract;" they cannot be instantiated directly, and a subclass of
an abstract class can only be instantiated directly if all inherited pure virtual methods
have been implemented by that class or a parent class. Pure virtual methods typically
have a declaration (signature) and no definition (implementation).
As an example, an abstract base class "MathSymbol" may provide a pure virtual
function doOperation(), and derived classes "Plus" and "Minus" implement
doOperation() to provide concrete implementations. Implementing doOperation()
would not make sense in the "MathSymbol" class as "MathSymbol" is an abstract
concept whose behaviour is defined solely for each given kind (subclass) of
"MathSymbol". Similarly, a given subclass of "MathSymbol" would not be complete
without an implementation of doOperation().
Although pure virtual methods typically have no implementation in the class that
declares them, pure virtual methods in C++ are permitted to contain an
implementation in their declaring class, providing fallback or default behaviour that a
derived class can delegate to if appropriate.
Pure virtual functions are also used where the method declarations are being used to
define an interface for which derived classes will supply all implementations. An
abstract class serving as an interface contains only pure virtual functions, and no data
members or ordinary methods. Use of purely abstract classes as interfaces works in
C++ as it supports multiple inheritance. Because many OO languages do not support
multiple inheritance they often provide a separate interface mechanism.
In C++, pure virtual functions are declared using a special syntax [=0] as
demonstrated below.
class Abstract {
public:
void Child::pure_virtual() {
Abstract::pure_virtual(); // the implementation in the abstract class
// is executed
}
The first expression is used to allocate memory to contain one single element of type
type. The second one is used to assign a block (an array) of elements of type type,
where number_of_elements is an integer value representing the amount of these. For
example:
int * bobby;
bobby = new int [5];
In this case, the system dynamically assigns space for five elements of type int and
returns a pointer to the first element of the sequence, which is assigned to bobby.
Therefore, now, bobby points to a valid block of memory with space for five elements
of type int.
The first element pointed by bobby can be accessed either with the expression
bobby[0] or the expression *bobby. Both are equivalent as has been explained in the
section about pointers. The second element can be accessed either with bobby[1] or
*(bobby+1) and so on...
You could be wondering the difference between declaring a normal array and assigning
dynamic memory to a pointer, as we have just done. The most important difference is
that the size of an array has to be a constant value, which limits its size to what we
decide at the moment of designing the program, before its execution, whereas the
dynamic memory allocation allows us to assign memory during the execution of the
program (runtime) using any variable or constant value as its size.
The dynamic memory requested by our program is allocated by the system from the
memory heap. However, computer memory is a limited resource, and it can be
exhausted. Therefore, it is important to have some mechanism to check if our request
to allocate memory was successful or not.
C++ provides two standard methods to check if the allocation was successful:
One is by handling exceptions. Using this method an exception of type bad_alloc is
thrown when the allocation fails. Exceptions are a powerful C++ feature explained later
in these tutorials. But for now you should know that if this exception is thrown and it is
not handled by a specific handler, the program execution is terminated.
This exception method is the default method used by new, and is the one used in a
declaration like:
The other method is known as nothrow, and what happens when it is used is that when
a memory allocation fails, instead of throwing a bad_alloc exception or terminating the
program, the pointer returned by new is a null pointer, and the program continues its
execution.
This method can be specified by using a special object called nothrow, declared in
header <new>, as argument for new:
bobby = new (nothrow) int [5];
In this case, if the allocation of this block of memory failed, the failure could be
detected by checking if bobby took a null pointer value:
int * bobby;
bobby = new (nothrow) int [5];
if (bobby == 0) {
// error assigning memory. Take measures.
};
This nothrow method requires more work than the exception method, since the value
returned has to be checked after each and every memory allocation, but I will use it in
our examples due to its simplicity. Anyway this method can become tedious for larger
projects, where the exception method is generally preferred. The exception method
will be explained in detail later in this tutorial.
delete pointer;
delete [] pointer;
The first expression should be used to delete memory allocated for a single element,
and the second one for memory allocated for arrays of elements.
The value passed as argument to delete must be either a pointer to a memory block
previously allocated with new, or a null pointer (in the case of a null pointer, delete
produces no effect).
#include <iostream>
#include <new>
int main ()
{
int i,n;
int * p;
cout << "How many numbers would you like to type? ";
cin >> i;
p= new (nothrow) int[i];
if (p == 0)
cout << "Error: memory could not be allocated";
else
{
for (n=0; n<i; n++)
{
[package declarations]
[import statements]
[class declaration]
package abc;
import java.lang;
class Demo
Sytem.out.println("Hello! World");
// method signatures
int turn(Direction direction, // An enum with values RIGHT, LEFT
double radius, double startSpeed, double endSpeed);
int changeLanes(Direction direction, double startSpeed, double endSpeed);
int signalTurn(Direction direction, boolean signalOn);
int getRadarFront(double distanceToCar, double speedOfCar);
int getRadarRear(double distanceToCar, double speedOfCar);
......
// more method signatures
}
Note that the method signatures have no braces and are terminated with a semicolon.
String Length
The length of a string is the number of characters that it contains. To obtain this value,
call the length( ) method, shown here:
int length( )
The following fragment prints “3”, since there are three characters in the string s:
String Concatenation
Here is an example:
// Using concatenation to prevent long lines.
class ConCat {
public static void main(String args[])
{
String longStr = "This could have been " +"a very long line that would have " +
"wrapped around. But string concatenation " +"prevents this.";
System.out.println(longStr);
}
}
InputStream and OutputStream are designed for byte streams. Reader and
Writer are designed for character streams. The byte stream classes and the character
stream classes form separate hierarchies. In general, you should use the character
stream classes when working with characters or strings, and use the byte stream
classes when working with bytes or other binary objects.
InputStream
InputStream is an abstract class that defines Java’s model of streaming byte input. All
of the methods in this class will throw an IOException on error conditions.
method Description
void close( ) Closes the input source. Further read attempts will
generate an IOException.
OutputStream
OutputStream is an abstract class that defines streaming byte output. All of the
methods in this class return a void value and throw an IOException in the case of
errors.
method Description
An Applet Skeleton
All but the most trivial applets override a set of methods that provides the basic
mechanism by which the browser or applet viewer interfaces to the applet and controls
its execution. Four of these methods—init( ), start( ), stop( ), and destroy( )—are
defined by Applet. Another, paint( ), is defined by the AWT Component class. Default
implementations for all of these methods are provided. Applets do not need to override
those methods they do not use. However, only very simple applets will not need to
define all of them. These five methods can be assembled into the skeleton shown here:
// An Applet skeleton.
import java.awt.*;
import java.applet.*;
/*
<applet code="AppletSkel" width=300 height=100>
</applet>
*/
Although this skeleton does not do anything, it can be compiled and run. When run, it
generates the following window when viewed with an applet viewer:
Q.28 write a program in java that will print following pattern on console
* *
* * *
* * * *
Q.29 write the program that will explain polymorphism in java using
interface?
Q.30 Write a program that will print “Hello Applet” in Applet? or write a
program that will print “Hello Applet” in status bar?