You are on page 1of 33

Notes C++ /Java- S.Y.Bsc.

Section –I Genesis

nQ.1 Explain the fundamental data type in C++

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.

//Program to illustrate various fundamental data type


#include<iostream.h>

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;

© Prof. Bhanudas satam Genesis -1


Notes C++ /Java- S.Y.Bsc. Section –I Genesis

Q.2 Explain the compilation of C++ Program

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

© Prof. Bhanudas satam Genesis -2


Notes C++ /Java- S.Y.Bsc. Section –I Genesis

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.

Q.3 Write a short notes on OOP


Object-oriented programming (OOP) is a programming paradigm that uses "objects"
and their interactions to design applications and computer programs. Programming
techniques may include features such as encapsulation, modularity, polymorphism,
and inheritance

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.

© Prof. Bhanudas satam Genesis -3


Notes C++ /Java- S.Y.Bsc. Section –I Genesis

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.

Q.4 Define some OOP Term


Along with each programming revolution comes a new set of terminology. There are
some new OOP concepts, but many have a simple analog in pre-OOP practice.

OOP Term Definition

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

class A struct with both data and functions


object Memory allocated to a class/struct. Often allocated with new.

member A field or function is a member of a class if it's defined in that class


constructor Function-like code that initializes new objects (structs) when they

© Prof. Bhanudas satam Genesis -4


Notes C++ /Java- S.Y.Bsc. Section –I Genesis

instantiated (allocated with new).


destructor Function-like code that is called when an object is deleted to free any
resources (eg, memory) that is has pointers to.
inheritance Defining a class (child) in terms of another class (parent). All of the
public members of the public class are available in the child class.
polymorphism Defining functions with the same name, but different parameters.

overload A function is overloaded if there is more than one definition. See


polymorphism.

override Redefine a function from a parent class in a child class.


subclass Same as child, derived, or inherited class.

superclass Same as parent or base class.


attribute Same as data member or member field.

Q.5 what is constructor? write types of constructor?


In object-oriented programming, a constructor in a class is a special block of
statements called when an object is created; Constructors are often distinguished by
having the same name as the declaring class. Their responsibility is to initialize the
object's data members and to establish the invariant of the class, failing if the invariant
isn't valid. A properly written constructor will leave the object in a 'valid' state
Example
public class Example
{
private int data;
//definition of the constructor.
public Example()
{
data=10;
}

//overloading a constructor
public Example(int input)
{
data = input;
}

//declaration of instance variable(s).

© Prof. Bhanudas satam Genesis -5


Notes C++ /Java- S.Y.Bsc. Section –I Genesis

There are following types of constructor

• Default constructor (Non-Parameterized constructor)

A default constructor is a constructor that either has no parameters, or if it has


parameters, all the parameters have default values.

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

A parameterized constructor is a constructor that either has parameters. When


object is created at that time we pass the parameter to object.

#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();

© Prof. Bhanudas satam Genesis -6


Notes C++ /Java- S.Y.Bsc. Section –I Genesis

return 0;
}

• Copy-constructor

A copy constructor is a special constructor in the C++ programming language


used to create a new object as a copy of an existing object. This constructor takes a
single argument: a reference to the object to be copied.
Normally the compiler automatically creates a copy constructor for each class
(known as an implicit copy constructor) but for special cases the programmer creates
the copy constructor, known as an explicit copy constructor. In such cases, the
compiler doesn't create one.
A copy constructor is generally needed when an object owns pointers or non-shareable
references, such as to a file, in which case a destructor and an assignment operator
should also be written
Q.6 what is destructor?
In object-oriented programming, a destructor is a method which is automatically
invoked when the object is destroyed. Its main purpose is to clean up and to free the
resources which were acquired by the object along its life cycle and unlink it from other
objects or resources invalidating any references in the process.
In C++, the destructor function is the same name as the class, but with a tilde
(~) in front of it. If the object was created locally, its destructor is automatically called,
and if the object was created with the new keyword, then its destructor is called when
the pointer that points to the object is deleted. This particular class holds a_pointer to
a list of character strings. A destructor is required when dynamically created data
elements were used, files were opened, locks have to be unlocked or a copy
constructor was used.
#include <string>
using namespace std;

class myclass {
public:
string* [] a_pointer;
void newstring(void)
{
a_pointer[current++] = new string();
}

~myclass() // THIS IS THE DESTRUCTOR METHOD


{
int n = 0;
while (n <= current)
delete a_pointer[n++];
}

© Prof. Bhanudas satam Genesis -7


Notes C++ /Java- S.Y.Bsc. Section –I Genesis

private:
int current;
};

Q.7 Write short notes on Copy Constructor?

A copy constructor is a special constructor in the C++ programming language used to


create a new object as a copy of an existing object. This constructor takes a single
argument: a reference to the object to be copied.

There are four cases where a copy constructor is called:

1. When an object is returned by value


2. When an object is passed (to a function) by value as an argument
3. When an object is constructed based on another object (of the same class)
4. When the compiler generates a temporary object (as in 1 and 2 above; as in
explicit casting, etc...)

Example

Copy constructor syntax


The copy constructor takes a reference to a const parameter. It is const to guarantee
that the copy constructor doesn't change it, and it is a reference because a value
parameter would require making a copy, which would invoke the copy constructor,
which would make a copy of its parameter, which would invoke the copy constructor,
which ...
Here is an example of a copy constructor for the Point class, which doesn't really need
one because the default copy constructor's action of copying fields would work fine, but
it shows how it works.

//=== file Point.h =============================================


class Point {
public:
. . .
Point(const Point& p); // copy constructor
. . .
//=== file Point.cpp ==========================================
. . .
Point::Point(const Point& p) {
x = p.x;

© Prof. Bhanudas satam Genesis -8


Notes C++ /Java- S.Y.Bsc. Section –I Genesis

y = p.y;
}
. . .
//=== file my_program.cpp ====================================
. . .
Point p; // calls default constructor
Point s = p; // calls copy constructor.
p = s; // assignment, not copy constructor.

Q.3 what is class? and the various categories of classes?

In object-oriented programming, a class is a programming language construct that is


used as a blueprint to create objects. This blueprint includes attributes and methods
that the created objects all share.

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.

© Prof. Bhanudas satam Genesis -9


Notes C++ /Java- S.Y.Bsc. Section –I Genesis

Most object oriented programming languages allow the programmer to specify which
classes are considered abstract and will not allow these to be instantiated.

Q.4 what are access specifier in class?


In C++, there are three access specifiers for classes: public, protected, and private.
These are important for encapsulation. A public member is one that can be accessed
by any code. A protected member can only be accessed by methods in the class and its
derived class. A private member can only be accessed by methods in the class itself.

Member access determines if a class member is accessible in an expression or


declaration. Suppose x is a member of class A. Class member x can be declared to
have one of the following levels of accessibility:

• public: x can be used anywhere without the access restrictions defined by


private or protected.
• private: x can be used only by the members and friends of class A.
• protected: x can be used only by the members and friends of class A, and the
members and friends of classes derived from class A.

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:

void f() class A


{
friend class C;
private:
int a;
public:
int b;
protected:
int c;
};

class B : A {

{
// a = 1;
b = 2;
c = 3;
}
};

class C {
void f(A x) {

© Prof. Bhanudas satam Genesis -10


Notes C++ /Java- S.Y.Bsc. Section –I Genesis

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.

Scope A::a A::b A::c

No access. Member A::a Access. Member A::b


function B::f() Access. Class B inherits from A.
is private. is public.

Access. Class C is a friend Access. Member A::b


function C::f() Access. Class C is a friend of A.
of A. is public.

object y in No access. Member y.a is Access. Member y.a is No access. Member y.c is
private. public. protected.
main()

No access. Member z.a is Access. Member z.a is No access. Member z.c is


object z in main()
private. public. protected.

Q.8 Function/method overloading and Constructor overloading?

Function/Method overloading is a feature found in various programming languages


such as C++ and Java that allows the creation of several methods with the same name
which differ from each other in terms of the type of the input and the type of the
output of the function.

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.

© Prof. Bhanudas satam Genesis -11


Notes C++ /Java- S.Y.Bsc. Section –I Genesis

Method overloading is usually associated with statically-typed programming languages


which enforce type checking in function calls. When overloading a method, you are
really just making a number of different methods that happen to have the same name.
It is resolved at compile time which of these methods are used.

In C++, another factor forces the overloading of function names:the constructor.


Because the constructor’s name is predetermined by the name of the class, it would
seem that there can be only one constructor. But what if you want to create an object
in more than one way? For example, suppose you build a class that can initialize itself
in a standard way and also by reading information from a file. You need two
constructors, one that takes no arguments (the default constructor) and one that takes
a string as an argument, which is the name of the file to initialize the object. Both are
constructors, so they must have the same name: the name of the class. Thus, function
overloading is essential to allow the same function name – the constructor in this case
– to be used with different argument types. In some object oriented programming
languages, constructors can also be overloaded. In languages that require constructors
to have the same name as the declaring class, constructor overloading allows multiple
ways of creating an object. The constructors must have different parameter types or
numbers of parameters.

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.

public class Person {


// instance variables:
String name;
String phoneNumber;

// Constructor with name and number:


public Person(String name, String phoneNumber){
this.name=name;
this.phoneNumber=phoneNumber;
}

// Alternative constructor without giving phone number.


// This will set the phone number to "N/A" (for "not available")
public Person(String name){
this(name, "N/A");
}
}

Q.9 what is “this” pointer?

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.

A static member function does not have a this pointer.

© Prof. Bhanudas satam Genesis -12


Notes C++ /Java- S.Y.Bsc. Section –I Genesis

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) {

// The 'this' pointer is used to retrieve 'xobj.a'


// hidden by the automatic variable 'a'
this->a = a;
}
void Print_a() { cout << "a = " << a << endl; }
};

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.

Q.10 what is inheritance?

In object-oriented programming, inheritance is a way to form new classes (instances of


which are called objects) using classes that have already been defined.

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

© Prof. Bhanudas satam Genesis -13


Notes C++ /Java- S.Y.Bsc. Section –I Genesis

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

Derived apple orange mango


class

Q.11 what is application of inheritance?

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

© Prof. Bhanudas satam Genesis -14


Notes C++ /Java- S.Y.Bsc. Section –I Genesis

Many object-oriented programming languages permit a class or object to replace the


implementation of an aspect—typically a behavior—that it has inherited. This process is
usually called overriding. Overriding introduces a complication: which version of the
behavior does an instance of the inherited class use—the one that is part of its own
class, or the one from the parent (base) class? The answer varies between
programming languages, and some languages provide the ability to indicate that a
particular behavior is not to be overridden and behave.

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.

Q.12 Explain different type of inheritance with the help of example?

Q.13 what is overriding?

Method overriding, in object oriented programming, is a language feature that allows a


subclass to provide a specific implementation of a method that is already provided by
one of its superclasses. The implementation in the subclass overrides (replaces) the
implementation in the superclass.
A subclass can give its own definition of methods which also happen to have the same
signature as the method in its superclass. This means that the subclass's method has
the same name and parameter list as the superclass's overridden method. Constraints
on the similarity of return type vary from language to language, as some languages
support covariance on return types.
Method overriding is an important feature that facilitates polymorphism in the design
of object-oriented programs.
Some languages allow the programmer to prevent a method from being overridden, or
disallow method overriding in certain core classes. This may or may not involve an
inability to subclass from a given class.

© Prof. Bhanudas satam Genesis -15


Notes C++ /Java- S.Y.Bsc. Section –I Genesis

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.

Q.14 what is operator overloading?

In computer programming, operator overloading (less commonly known as operator


ad-hoc polymorphism) is a specific case of polymorphism in which some or all of
operators like +, =, or == have different implementations depending on the types of
their arguments. Sometimes the overloadings are defined by the language; sometimes
the programmer can implement support for new types.
Operator overloading is useful because it allows the developer to program using
notation closer to the target domain and allows user types to look like types built into
the language. It can easily be emulated using function calls; for an example, consider
the integers a, b, c:

Q.15 Explain Unary operator overloading with help of example?

#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; }

ThreeD operator++(); // prefix version of ++

void show() ;
} ;

// Overload the prefix version of ++.


ThreeD ThreeD::operator++()
{
x++; // increment x, y, and z
y++;
z++;
return *this;
}

// Show X, Y, Z coordinates.
void ThreeD::show()
{
cout << x << ", ";
cout << y << ", ";
cout << z << "\n";
}

© Prof. Bhanudas satam Genesis -16


Notes C++ /Java- S.Y.Bsc. Section –I Genesis

int main()
{
ThreeD a(1, 2, 3);

cout << "Original value of a: ";


a.show();

++a; // increment a
cout << "Value after ++a: ";
a.show();

return 0;
}

Q.16 Explain Operator returning value with help of example?

#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";
}

Point operator+(Point op2);


Point operator-(Point op2);
Point operator=(Point op2);
Point operator++();
};

// Overload + for Point.


Point Point::operator+(Point op2)
{
Point temp;

temp.x = op2.x + x;
temp.y = op2.y + y;

return temp;
}

// Overload - for Point.


Point Point::operator-(Point op2)
{
Point temp;

© Prof. Bhanudas satam Genesis -17


Notes C++ /Java- S.Y.Bsc. Section –I Genesis

// notice order of operands


temp.x = x - op2.x;
temp.y = y - op2.y;

return temp;
}

// Overload asignment for Point.


Point Point::operator=(Point op2)
{
x = op2.x;
y = op2.y;

return *this; // i.e., return object that generated call


}

// Overload prefix ++ for Point.


Point Point::operator++()
{
x++;
y++;

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

ob1 = ob2 = ob3; // multiple assignment


ob1.show(); // displays 90 90
ob2.show(); // displays 90 90

return 0;
}

Q.17 Explain Binary operator overloading with help of example?

use above example (Write a program for addition of complex number)

Q.18 Explain Overloading arithmetic with help of example?

#include <iostream>
using namespace std;

© Prof. Bhanudas satam Genesis -18


Notes C++ /Java- S.Y.Bsc. Section –I Genesis

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; }

ThreeD operator+(ThreeD op2); // op1 is implied


ThreeD operator=(ThreeD op2); // op1 is implied
ThreeD operator-(ThreeD op2); // op1 is implied
void show() ;
};
// Overload subtraction.
ThreeD ThreeD::operator-(ThreeD op2)
{
ThreeD temp;

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;

cout << "Original value of a: ";


a.show();

© Prof. Bhanudas satam Genesis -19


Notes C++ /Java- S.Y.Bsc. Section –I Genesis

cout << "Original value of b: ";


b.show();

c = a - c;
cout << "a - c: ";
c.show();

cout << "\n";

return 0;
}

Q.19 Explain relational and assignment operators

#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) {}

double volume() const {


return length*width*height;
}

double getLength() const { return length; }


double getWidth() const { return width; }
double getHeight() const { return height; }

inline bool operator<(const Box& aBox) const {


return volume() < aBox.volume();
}

inline bool operator<(const double aValue) const {


return volume() < aValue;
}

private:
double length;
double width;
double height;
};

int main() {

© Prof. Bhanudas satam Genesis -20


Notes C++ /Java- S.Y.Bsc. Section –I Genesis

Box firstBox(17.0, 11.0, 5.0);

if(firstBox < 100000){


cout << "less than";
}else{
cout << "not less than";
}

return 0;
}

Q.20 what is polymorphism? Explain static and dynamic polymorphism?

Generally, the ability to appear in many forms. In object-oriented programming,


polymorphism refers to a programming language's ability to process objects differently
depending on their data type or class. More specifically, it is the ability to redefine
methods for derived classes. For example, given a base class shape, polymorphism
enables the programmer to define different area methods for any number of derived
classes, such as circles, rectangles and triangles. No matter what shape an object is,
applying the area method to it will return the correct results. Polymorphism is
considered to be a requirement of any true object-oriented programming language
(OOPL).

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.

C++ supports polymorphism of 2 kinds - polymorphism of types (Templates) and


polymorphism of behavior (Virtual methods and inheritance). Sometimes one could
simulate polymorphism of types using inheritance (Deriving all types from a common
base class and implementing generic algorithms to use base class pointers) and also
do polymorphism of behavior using templates (Policy based design). Doing
polymorphism of types using inheritance is a highly flawed approach where one loses
speed, type safety and convenience. This is done only by users who are too scared to
use templates. However, doing polymorphism of behavior using templates, can be a
good thing sometimes. Since templates lead to faster and safer code (The abstract -
concrete binding happens at compile time instead of at runtime, so faster, and more
type safe), one must actively seek to simulate both forms of polymorphism (Types and
Behavior) using templates. Of course, there are certain things which absolutely require
inheritance and virtual methods. One example is that while designing OO frameworks,
often the implementation would need to have 'Heterogeneous containers', and this is
not possible using templates. So, in such cases, of course we'd have to employ
inheritance and virtual functions. But in many other cases, templates could be
employed to simulate both forms of polymorphism and actually leads to faster and
safer code. I recently gave a small talk that compared the 2 forms of polymorphism in
C++.

Q.21 what is virtual function? Explain pure virtual function?

© Prof. Bhanudas satam Genesis -21


Notes C++ /Java- S.Y.Bsc. Section –I Genesis

In object-oriented programming, a virtual function or virtual method is one whose


behavior can be overridden within an inheriting class by a function with the same
signature. This concept is a very important part of the polymorphism portion of object-
oriented programming (OOP).

The concept of the virtual function solves the following problem:

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.

© Prof. Bhanudas satam Genesis -22


Notes C++ /Java- S.Y.Bsc. Section –I Genesis

In C++, pure virtual functions are declared using a special syntax [=0] as
demonstrated below.
class Abstract {
public:

virtual void pure_virtual() = 0;


};
The pure virtual function declaration provides only the prototype of the method.
Although an implementation of the pure virtual function is typically not provided in an
abstract class, it may be included, although the definition may not be included at the
point of declaration [1]. Every non-abstract child class is still required to override the
method, but the implementation provided by the abstract class may be called in this
way:
void Abstract::pure_virtual() {
// do something
}

class Child : public Abstract {


virtual void pure_virtual(); // no longer abstract, this class may be
// instantiated.
};

void Child::pure_virtual() {
Abstract::pure_virtual(); // the implementation in the abstract class
// is executed
}

Q.22 Explain dynamic allocation operators?

In computer science, dynamic memory allocation is the allocation of memory storage


for use in a computer program during the runtime of that program.
The answer is dynamic memory, for which C++ integrates the operators new and
delete.

Operators new and new[]


In order to request dynamic memory we use the operator new. new is followed
by a data type specifier and -if a sequence of more than one element is required- the
number of these within brackets []. It returns a pointer to the beginning of the new
block of memory allocated. Its form is:

pointer = new type


pointer = new type [number_of_elements]

© Prof. Bhanudas satam Genesis -23


Notes C++ /Java- S.Y.Bsc. Section –I Genesis

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

© Prof. Bhanudas satam Genesis -24


Notes C++ /Java- S.Y.Bsc. Section –I Genesis

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:

bobby = new int [5]; // if it fails an exception is thrown

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

© Prof. Bhanudas satam Genesis -25


Notes C++ /Java- S.Y.Bsc. Section –I Genesis

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.

Operators delete and delete[]


Since the necessity of dynamic memory is usually limited to specific moments within a
program, once it is no longer needed it should be freed so that the memory becomes
available again for other requests of dynamic memory. This is the purpose of the
operator delete, whose format is:

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++)
{

© Prof. Bhanudas satam Genesis -26


Notes C++ /Java- S.Y.Bsc. Section –I Genesis

cout << "Enter number: ";


cin >> p[n];
}
cout << "You have entered: ";
for (n=0; n<i; n++)
cout << p[n] << ", ";
delete[] p;
}
return 0;
}

Q.23 Explain the structure of Java program?

Every Java program consists of a collection of classes--nothing else. A class is a


template for creating a particular form of object. Each object created by the template
contains the same members, each of which is either a field or a method. A field is a
“container'' that holds a value. A method is an operation on the fields of the object and
any values that are passed as arguments to the method. The objects created by a
particular class template are called the instances or objects of that class. Each instance
contains the members specified in the class template.

[package declarations]

[import statements]

[class declaration]

package abc;

import java.lang;

class Demo

public static void main(String[] args)

Sytem.out.println("Hello! World");

Package: A package is a namespace that organizes a set of related classes and


interfaces

© Prof. Bhanudas satam Genesis -27


Notes C++ /Java- S.Y.Bsc. Section –I Genesis

Q.24 what is an interface?

In the Java programming language, an interface is a reference type, similar to a class,


that can contain only constants, method signatures, and nested types. There are no
method bodies. Interfaces cannot be instantiated—they can only be implemented by
classes or extended by other interfaces.

Defining an interface is similar to creating a new class:

public interface OperateCar {

// constant declarations, if any

// 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.

Q.25 Explain string handling in Java?

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:

char chars[] = { 'a', 'b', 'c' };


String s = new String(chars);
System.out.println(s.length());

String Concatenation

For example, the following fragment concatenates three strings:

String age = "9";


String s = "He is " + age + " years old.";
System.out.println(s);

© Prof. Bhanudas satam Genesis -28


Notes C++ /Java- S.Y.Bsc. Section –I Genesis

This displays the string “He is 9 years old.”


One practical use of string concatenation is found when you are creating very long
strings. Instead of letting long strings wrap around within your source code, you can
break them into smaller pieces, using the + to concatenate them.

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);
}
}

Q.26 Explain the stream Input/Output classes in Java?

The Stream Classes

Java’s stream-based I/O is built upon four abstract classes: InputStream,


OutputStream, Reader, and Writer. These classes were briefly discussed in Chapter 12.
They are used to create several concrete stream subclasses. Although your programs
perform their I/O operations through concrete subclasses, the top-level classes define
the basic functionality common to all stream classes.

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

int read( ) Returns an integer representation of the next


available byte of input. –1 is returned when the
end of the file is encountered

void close( ) Closes the input source. Further read attempts will
generate an IOException.

© Prof. Bhanudas satam Genesis -29


Notes C++ /Java- S.Y.Bsc. Section –I Genesis

© Prof. Bhanudas satam Genesis -30


Notes C++ /Java- S.Y.Bsc. Section –I Genesis

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

int write (byte buffer[] ) Writes a complete array of bytes to an output


stream.

void close( ) Closes the output stream. Further write attempts


will generate an IOException.

Q.27 what is an applet? Explain the skeleton of applet?

An applet is a window-based program. As such, its architecture is different from the


so-called normal, console-based programs.

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>
*/

public class AppletSkel extends Applet {


// Called first.
public void init() {
// initialization
}
/* Called second, after init(). Also called whenever

© Prof. Bhanudas satam Genesis -31


Notes C++ /Java- S.Y.Bsc. Section –I Genesis

the applet is restarted. */

© Prof. Bhanudas satam Genesis -32


Notes C++ /Java- S.Y.Bsc. Section –I Genesis

public void start() {


// start or resume execution
}
// Called when the applet is stopped.

public void stop() {


// suspends execution
}

/* Called when applet is terminated. This is the last method executed. */

public void destroy() {


// perform shutdown activities
}

// Called when an applet's window must be restored.


public void paint(Graphics g) {
// redisplay contents of window
}
}

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?

© Prof. Bhanudas satam Genesis -33