You are on page 1of 85

ANNEXURE 1 – ASSIGNMENT QUESTIONS:

UNIT-1:OBJECTS AND CLASSES

Mention the advantages of writing functions.

Give the syntax to write functions.

What do you mean by Call by reference?

How will you declare a reference variable in C++?

What do you mean by Inline functions?

How will you make a function Inline?

Default parameters are assigned from ________ to ___________ .

What do you mean by function overloading?

Is the following set of function overloaded

int mul(int m,int n)

float mul(int k,int j)

What is the default value for static integer value?

How will you make a variable static?

A static function can access only static variables (TRUE/FALSE)

Assume that c1 is a class and fn() is a static function then how will you call the function f1()

A constant object is required to invoke a constant class (TRUE/FALSE)

UNIT-2:CONSTRUCTORS

What is a constructer?

Is it possible to overload constructer?

What is purpose of copy constructer?


What is a destructor?

Is it possible to overload destructor?

Objects are passed in call by __________ method

When we overload a operator will its meaning change ?

Give the general form of operator function

Write examples for unary and binary operators

Which operator cannot overloaded using friend function ?

UNIT-3:TEMPLATES

What do you mean by Generic programming?

What do you mean by function templates?

Write the syntax for creating function templates.

How overloaded function template is called?

When you will create a class template?

Write the syntax for creating class templates.

Give some examples for compile time errors.

What are the two categories of exceptions?

Mention the steps to handle synchronous exceptions.

Give the general form of try catch block.

When will the catch block gets executed ?

Give the general form of throw statement

How will you call a function that generates exception?

Mention the different form of throw statement

How catch handlers are examined in a try block.

Write the syntax of the catch handler that can catch all exceptions
Write the syntax of rethrowing exceptions.

Is it possible to rethrow an exception outside catch block ?

UNIT-4:INHERITANCE

What is Inheritance?

Mention the various inheritance schemes supported in C++.

Draw the scheme for single inheritance

Write the syntax for implementing single inheritance.

If a base class is inherited in private mode, how its public members appears for the derived class

If a base class is inherited in public mode, all the members of the class appears as public
members to the derived class (TRUE/FALSE)

What is the special access specifier used for inheritance?

List the access specifiers available in C++.

What is multiple inheritance?

Multiple inheritance is supported in _________ and not supported in__________

Multilevel inheritance is special form of Multiple inheritance (TRUE/FALSE)

Virtual functions achieves ____________ form of polymorphism

When binding happens at run time we call it as ____________

List the advantages of creating object pointers to base classes.

Constrcuters are inherited (TRUE /FALSE)

Destructors are not inherited (TRUE/FALSE)

What happens if base class is declared virtual?

In which order the keywords virtual and public must appear in the derived class?

How will you declare a pure virtual function?

Objects cannot be created for abstract class (TRUE/FALSE)


UNIT-5:FILE HANDLING

What is a stream ?

What are the two types of streams?

List some classes available in fstream header file?

if we want have a input and output operations on a file which type of object we create?

Write any two file opening modes?

What is a random access fle?

Write the two seek pointers available in random access files

1. What is a class?
2. What is an object?
3. What is the difference between an object and a class?
4. What is the difference between class and structure?
5. What is public, protected, private?
6. What are virtual functions?
7. What is friend function?
8. What is a scope resolution operator?
9. What do you mean by inheritance?
10. What is abstraction?
11. What is polymorphism? Explain with an example.
12. What is encapsulation?
13. What do you mean by binding of data and functions?
14. What is function overloading and operator overloading?
15. What is virtual class and friend class?
16. What do you mean by inline function?
17. What do you mean by public, private, protected and friendly?
18. When is an object created and what is its lifetime?
19. What do you mean by multiple inheritance and multilevel inheritance? Differentiate between
them.
20. Difference between realloc() and free?
21. What is a template?
22. What are the main differences between procedure oriented languages and object oriented
languages?
23. What is R T T I ?
24. What are generic functions and generic classes?
25. What is namespace?
26. What is the difference between pass by reference and pass by value?
27. Why do we use virtual functions?
28. What do you mean by pure virtual functions?
29. What are virtual classes?
30. Does c++ support multilevel and multiple inheritance?
31. What are the advantages of inheritance?
32. When is a memory allocated to a class?
33. What is the difference between declaration and definition?
34. What is virtual constructors/destructors?
35. In c++ there is only virtual destructors, no constructors. Why?
36. What is late bound function call and early bound function call? Differentiate.
37. How is exception handling carried out in c++?
38. When will a constructor executed?
39. What is Dynamic Polymorphism?
40. Write a macro for swapping integers.

• Define namespace.
It is a feature in c++ to minimize name collisions in the global name space. This
namespace keyword assigns a distinct name to a library that allows other libraries to use
the same identifier names without creating any name collisions. Furthermore, the
compiler uses the namespace signature for differentiating the definitions.
• What is the use of ‘using’ declaration.
A using declaration makes it possible to use a name from a namespace without the scope
operator.
• What is an Iterator class?
A class that is used to traverse through the objects maintained by a container class. There
are five categories of iterators:
Ø input iterators,
Ø output iterators,
Ø forward iterators,
Ø bidirectional iterators,
Ø random access.
An iterator is an entity that gives access to the contents of a container object without
violating encapsulation constraints. Access to the contents is granted on a one-at-a-time
basis in order. The order can be storage order (as in lists and queues) or some arbitrary
order (as in array indices) or according to some ordering relation (as in an ordered binary
tree). The iterator is a construct, which provides an interface that, when called, yields
either the next element in the container, or some value denoting the fact that there are no
more elements to examine. Iterators hide the details of access to and update of the
elements of a container class.
The simplest and safest iterators are those that permit read-only access to the contents of
a container class. The following code fragment shows how an iterator might appear in
code:
cont_iter:=new cont_iterator();
x:=cont_iter.next();
while x/=none do
...
s(x);
...
x:=cont_iter.next();
end;
In this example, cont_iter is the name of the iterator. It is created on the first line by
instantiation of cont_iterator class, an iterator class defined to iterate over some container
class, cont. Succesive elements from the container are carried to x. The loop terminates
when x is bound to some empty value. (Here, none)In the middle of the loop, there is s(x)
an operation on x, the current element from the container. The next element of the
container is obtained at the bottom of the loop.

• List out some of the OODBMS available.

Ø GEMSTONE/OPAL of Gemstone systems.


Ø ONTOS of Ontos.
Ø Objectivity of Objectivity inc.
Ø Versant of Versant object technology.
Ø Object store of Object Design.
Ø ARDENT of ARDENT software.
Ø POET of POET software.

• List out some of the object-oriented methodologies.

Ø Object Oriented Development (OOD) (Booch 1991,1994).


Ø Object Oriented Analysis and Design (OOA/D) (Coad and Yourdon 1991).
Ø Object Modelling Techniques (OMT) (Rumbaugh 1991).
Ø Object Oriented Software Engineering (Objectory) (Jacobson 1992).
Ø Object Oriented Analysis (OOA) (Shlaer and Mellor 1992).
Ø The Fusion Method (Coleman 1991).
• What is an incomplete type?
Incomplete types refers to pointers in which there is non availability of the
implementation of the referenced location or it points to some location whose value is not
available for modification.
Example:
int *i=0x400 // i points to address 400
*i=0; //set the value of memory location pointed by i.
Incomplete types are otherwise called uninitialized pointers.
• What is a dangling pointer?
A dangling pointer arises when you use the address of an object after its lifetime is over.
This may occur in situations like returning addresses of the automatic variables from a
function or using the address of the memory block after it is freed.
• Differentiate between the message and method.
Message Method
Objects communicate by sending messages Provides response to a message.
to each other.
A message is sent to invoke a method. It is an implementation of an operation.
• What is an adaptor class or Wrapper class?
A class that has no functionality of its own. Its member functions hide the use of a third
party software component or an object with the non-compatible interface or a non-
object- oriented implementation.
• What is a Null object?
It is an object of some class whose purpose is to indicate that a real object of that class
does not exist. One common use for a null object is a return value from a member
function that is supposed to return an object with some specified properties but cannot
find such an object.
• What is class invariant?
A class invariant is a condition that defines all valid states for an object. It is a logical
condition to ensure the correct working of a class. Class invariants must hold when an
object is created, and they must be preserved under all operations of the class. In
particular all class invariants are both preconditions and post-conditions for all operations
or member functions of the class.
• What do you mean by Stack unwinding?
It is a process during exception handling when the destructor is called for all local objects
between the place where the exception was thrown and where it is caught.
• Define precondition and post-condition to a member function.
Precondition:
A precondition is a condition that must be true on entry to a member function. A
class is used correctly if preconditions are never false. An operation is not responsible for
doing anything sensible if its precondition fails to hold.
For example, the interface invariants of stack class say nothing about pushing yet another
element on a stack that is already full. We say that isful() is a precondition of the push
operation.

Post-condition:
A post-condition is a condition that must be true on exit from a member function
if the precondition was valid on entry to that function. A class is implemented correctly if
post-conditions are never false.
For example, after pushing an element on the stack, we know that isempty() must
necessarily hold. This is a post-condition of the push operation.
• What are the conditions that have to be met for a condition to be an invariant of the class?
Ø The condition should hold at the end of every constructor.
Ø The condition should hold at the end of every mutator(non-const) operation.
• What are proxy objects?
Objects that stand for other objects are called proxy objects or surrogates.
Example:
template
class Array2D
{
public:
class Array1D
{
public:
T& operator[] (int index);
const T& operator[] (int index) const;
...
};
Array1D operator[] (int index);
const Array1D operator[] (int index) const;
...
};

The following then becomes legal:


Array2Ddata(10,20);
........
cout<

Here data[3] yields an Array1D object and the operator [] invocation on that
object yields the float in position(3,6) of the original two dimensional array. Clients of
the Array2D class need not be aware of the presence of the Array1D class. Objects of this
latter class stand for one-dimensional array objects that, conceptually, do not exist for
clients of Array2D. Such clients program as if they were using real, live, two-dimensional
arrays. Each Array1D object stands for a one-dimensional array that is absent from a
conceptual model used by the clients of Array2D. In the above example, Array1D is a
proxy class. Its instances stand for one-dimensional arrays that, conceptually, do not
exist.
• Name some pure object oriented languages.
Ø Smalltalk,
Ø Java,
Ø Eiffel,
Ø Sather.
• Name the operators that cannot be overloaded.
sizeof . .* .-> :: ?:
• What is a node class?
A node class is a class that,
Ø relies on the base class for services and implementation,
Ø provides a wider interface to te users than its base class,
Ø relies primarily on virtual functions in its public interface
Ø depends on all its direct and indirect base class
Ø can be understood only in the context of the base class
Ø can be used as base for further derivation
Ø can be used to create objects.
A node class is a class that has added new services or functionality beyond the services
inherited from its base class.
• What is an orthogonal base class?
If two base classes have no overlapping methods or data they are said to be independent
of, or orthogonal to each other. Orthogonal in the sense means that two classes operate in
different dimensions and do not interfere with each other in any way. The same derived
class may inherit such classes with no difficulty.
• What is a container class? What are the types of container classes?
A container class is a class that is used to hold objects in memory or external storage. A
container class acts as a generic holder. A container class has a predefined behavior and a
well-known interface. A container class is a supporting class whose purpose is to hide the
topology used for maintaining the list of objects in memory. When a container class
contains a group of mixed objects, the container is called a heterogeneous container;
when the container is holding a group of objects that are all the same, the container is
called a homogeneous container.
• What is a protocol class?
An abstract class is a protocol class if:
Ø it neither contains nor inherits from classes that contain member data, non-virtual
functions, or private (or protected) members of any kind.
Ø it has a non-inline virtual destructor defined with an empty implementation,
Ø all member functions other than the destructor including inherited functions, are
declared pure virtual functions and left undefined.
• What is a mixin class?
A class that provides some but not all of the implementation for a virtual base class is
often called mixin. Derivation done just for the purpose of redefining the virtual functions
in the base classes is often called mixin inheritance. Mixin classes typically don't share
common bases.
• What is a concrete class?
A concrete class is used to define a useful object that can be instantiated as an automatic
variable on the program stack. The implementation of a concrete class is defined. The
concrete class is not intended to be a base class and no attempt to minimize dependency
on other classes in the implementation or behavior of the class.
• What is the handle class?
A handle is a class that maintains a pointer to an object that is programmatically
accessible through the public interface of the handle class.
Explanation:
In case of abstract classes, unless one manipulates the objects of these classes through
pointers and references, the benefits of the virtual functions are lost. User code may
become dependent on details of implementation classes because an abstract type cannot
be allocated statistically or on the stack without its size being known. Using pointers or
references implies that the burden of memory management falls on the user. Another
limitation of abstract class object is of fixed size. Classes however are used to represent
concepts that require varying amounts of storage to implement them.
A popular technique for dealing with these issues is to separate what is used as a single
object in two parts: a handle providing the user interface and a representation holding all
or most of the object's state. The connection between the handle and the representation is
typically a pointer in the handle. Often, handles have a bit more data than the simple
representation pointer, but not much more. Hence the layout of the handle is typically
stable, even when the representation changes and also that handles are small enough to
move around relatively freely so that the user needn’t use the pointers and the
references.
• What is an action class?
The simplest and most obvious way to specify an action in C++ is to write a function.
However, if the action has to be delayed, has to be transmitted 'elsewhere' before being
performed, requires its own data, has to be combined with other actions, etc then it often
becomes attractive to provide the action in the form of a class that can execute the desired
action and provide other services as well. Manipulators used with iostreams is an obvious
example.
Explanation:
A common form of action class is a simple class containing just one virtual
function.
class Action
{
public:
virtual int do_it( int )=0;
virtual ~Action( );
}
Given this, we can write code say a member that can store actions for later execution
without using pointers to functions, without knowing anything about the objects
involved, and without even knowing the name of the operation it invokes. For example:
class write_file : public Action
{
File& f;
public:
int do_it(int)
{
return fwrite( ).suceed( );
}
};
class error_message: public Action
{
response_box db(message.cstr( ),"Continue","Cancel","Retry");
switch (db.getresponse( ))
{
case 0: return 0;
case 1: abort();
case 2: current_operation.redo( );return 1;
}
};

A user of the Action class will be completely isolated from any knowledge of derived
classes such as write_file and error_message.
• When can you tell that a memory leak will occur?
A memory leak occurs when a program loses the ability to free a block of dynamically
allocated memory.
• What is a parameterized type?
A template is a parameterized construct or type containing generic code that can use or
manipulate any type. It is called parameterized because an actual type is a parameter of
the code body. Polymorphism may be achieved through parameterized types. This type of
polymorphism is called parameteric polymorphism. Parameteric polymorphism is the
mechanism by which the same code is used on different types passed as parameters.

• Differentiate between a deep copy and a shallow copy?

Deep copy involves using the contents of one object to create another instance of the same class.
In a deep copy, the two objects may contain ht same information but the target object will have
its own buffers and resources. the destruction of either object will not affect the remaining
object. The overloaded assignment operator would create a deep copy of objects.
Shallow copy involves copying the contents of one object into another instance of the same class
thus creating a mirror image. Owing to straight copying of references and pointers, the two
objects will share the same externally contained contents of the other object to be unpredictable.
Explanation:
Using a copy constructor we simply copy the data values member by member. This method of
copying is called shallow copy. If the object is a simple class, comprised of built in types and no
pointers this would be acceptable. This function would use the values and the objects and its
behavior would not be altered with a shallow copy, only the addresses of pointers that are
members are copied and not the value the address is pointing to. The data values of the object
would then be inadvertently altered by the function. When the function goes out of scope, the
copy of the object with all its data is popped off the stack.
If the object has any pointers a deep copy needs to be executed. With the deep copy of an object,
memory is allocated for the object in free store and the elements pointed to are copied. A deep
copy is used for objects that are returned from a function.

• What is an opaque pointer?


A pointer is said to be opaque if the definition of the type to which it points to is not
included in the current translation unit. A translation unit is the result of merging an
implementation file with all its headers and header files.
• What is a smart pointer?
A smart pointer is an object that acts, looks and feels like a normal pointer but offers
more functionality. In C++, smart pointers are implemented as template classes that
encapsulate a pointer and override standard pointer operators. They have a number of
advantages over regular pointers. They are guaranteed to be initialized as either null
pointers or pointers to a heap object. Indirection through a null pointer is checked. No
delete is ever necessary. Objects are automatically freed when the last pointer to them has
gone away. One significant problem with these smart pointers is that unlike regular
pointers, they don't respect inheritance. Smart pointers are unattractive for polymorphic
code. Given below is an example for the implementation of smart pointers.
Example:
template
class smart_pointer
{
public:
smart_pointer(); // makes a null pointer
smart_pointer(const X& x) // makes pointer to copy of x

X& operator *( );
const X& operator*( ) const;
X* operator->() const;

smart_pointer(const smart_pointer &);


const smart_pointer & operator =(const smart_pointer&);
~smart_pointer();
private:
//...
};
This class implement a smart pointer to an object of type X. The object itself is located on
the heap. Here is how to use it:
smart_pointer p= employee("Harris",1333);
Like other overloaded operators, p will behave like a regular pointer,
cout<<*p;
p->raise_salary(0.5);
• What is reflexive association?
The 'is-a' is called a reflexive association because the reflexive association permits
classes to bear the is-a association not only with their super-classes but also with
themselves. It differs from a 'specializes-from' as 'specializes-from' is usually used to
describe the association between a super-class and a sub-class. For example:
Printer is-a printer.
• What is slicing?
Slicing means that the data added by a subclass are discarded when an object of the
subclass is passed or returned by value or from a function expecting a base class
object.
Explanation:
Consider the following class declaration:
class base
{
...
base& operator =(const base&);
base (const base&);
}
void fun( )
{
base e=m;
e=m;
}
As base copy functions don't know anything about the derived only the base part of the
derived is copied. This is commonly referred to as slicing. One reason to pass objects of
classes in a hierarchy is to avoid slicing. Other reasons are to preserve polymorphic
behavior and to gain efficiency.
• What is name mangling?
Name mangling is the process through which your c++ compilers give each function in
your program a unique name. In C++, all programs have at-least a few functions with the
same name. Name mangling is a concession to the fact that linker always insists on all
function names being unique.
Example:
In general, member names are made unique by concatenating the name of the
member with that of the class e.g. given the declaration:
class Bar
{
public:
int ival;
...
};
ival becomes something like:
// a possible member name mangling
ival__3Bar
Consider this derivation:
class Foo : public Bar
{
public:
int ival;
...
}
The internal representation of a Foo object is the concatenation of its base and derived
class members.
// Pseudo C++ code
// Internal representation of Foo
class Foo
{
public:
int ival__3Bar;
int ival__3Foo;
...
};
Unambiguous access of either ival members is achieved through name mangling.
Member functions, because they can be overloaded, require an extensive mangling to
provide each with a unique name. Here the compiler generates the same name for the two
overloaded instances(Their argument lists make their instances unique).
• What are proxy objects?
Objects that points to other objects are called proxy objects or surrogates. Its an object
that provides the same interface as its server object but does not have any functionality.
During a method invocation, it routes data to the true server object and sends back the
return value to the object.
• Differentiate between declaration and definition in C++.
A declaration introduces a name into the program; a definition provides a unique
description of an entity (e.g. type, instance, and function). Declarations can be repeated in
a given scope, it introduces a name in a given scope. There must be exactly one definition
of every object, function or class used in a C++ program.
A declaration is a definition unless:
Ø it declares a function without specifying its body,
Ø it contains an extern specifier and no initializer or function body,
Ø it is the declaration of a static class data member without a class definition,
Ø it is a class name definition,
Ø it is a typedef declaration.
A definition is a declaration unless:
Ø it defines a static class data member,
Ø it defines a non-inline member function.
• What is cloning?
An object can carry out copying in two ways i.e. it can set itself to be a copy of another
object, or it can return a copy of itself. The latter process is called cloning.
• Describe the main characteristics of static functions.
The main characteristics of static functions include,
Ø It is without the a this pointer,
Ø It can't directly access the non-static members of its class
Ø It can't be declared const, volatile or virtual.
Ø It doesn't need to be invoked through an object of its class, although for convenience,
it may.
• Will the inline function be compiled as the inline function always? Justify.
An inline function is a request and not a command. Hence it won't be compiled as an
inline function always.
Explanation:
Inline-expansion could fail if the inline function contains loops, the address of an
inline function is used, or an inline function is called in a complex expression. The rules
for inlining are compiler dependent.
• Define a way other than using the keyword inline to make a function inline.
The function must be defined inside the class.
• How can a '::' operator be used as unary operator?
The scope operator can be used to refer to members of the global namespace. Because the
global namespace doesn’t have a name, the notation :: member-name refers to a member
of the global namespace. This can be useful for referring to members of global
namespace whose names have been hidden by names declared in nested local scope.
Unless we specify to the compiler in which namespace to search for a declaration, the
compiler simple searches the current scope, and any scopes in which the current scope is
nested, to find the declaration for the name.
• What is placement new?
When you want to call a constructor directly, you use the placement new. Sometimes you
have some raw memory that's already been allocated, and you need to construct an object
in the memory you have. Operator new's special version placement new allows you to do
it.
class Widget
{
public :
Widget(int widgetsize);
...
Widget* Construct_widget_int_buffer(void *buffer,int widgetsize)
{
return new(buffer) Widget(widgetsize);
}
};
This function returns a pointer to a Widget object that's constructed within the
buffer passed to the function. Such a function might be useful for applications using
shared memory or memory-mapped I/O, because objects in such applications must be
placed at specific addresses or in memory allocated by special routines.
• OOAD
What do you mean by analysis and design?
Analysis:
Basically, it is the process of determining what needs to be done before how it should be
done. In order to accomplish this, the developer refers the existing systems and
documents. So, simply it is an art of discovery.
Design:
It is the process of adopting/choosing the one among the many, which best accomplishes
the users needs. So, simply, it is compromising mechanism.
• What are the steps involved in designing?
Before getting into the design the designer should go through the SRS prepared by the
System Analyst.
The main tasks of design are Architectural Design and Detailed Design.
In Architectural Design we find what are the main modules in the problem
domain.
In Detailed Design we find what should be done within each module.
• What are the main underlying concepts of object orientation?
Objects, messages, class, inheritance and polymorphism are the main concepts of object
orientation.
• What do u meant by "SBI" of an object?
SBI stands for State, Behavior and Identity. Since every object has the above three.
Ø State:
It is just a value to the attribute of an object at a particular time.
Ø Behaviour:
It describes the actions and their reactions of that object.
Ø Identity:
An object has an identity that characterizes its own existence. The identity makes it
possible to distinguish any object in an unambiguous way, and independently from its
state.
• Differentiate persistent & non-persistent objects?
Persistent refers to an object's ability to transcend time or space. A persistent object
stores/saves its state in a permanent storage system with out losing the information
represented by the object.
A non-persistent object is said to be transient or ephemeral. By default objects are
considered as non-persistent.
• What do you meant by active and passive objects?
Active objects are one which instigate an interaction which owns a thread and they are
responsible for handling control to other objects. In simple words it can be referred as
client.
Passive objects are one, which passively waits for the message to be processed. It waits
for another object that requires its services. In simple words it can be referred as server.
• What is meant by software development method?
Software development method describes how to model and build software systems in a
reliable and reproducible way. To put it simple, methods that are used to represent ones'
thinking using graphical notations.
• What are models and meta models?
Model:
It is a complete description of something (i.e. system).
Meta model:
It describes the model elements, syntax and semantics of the notation that allows their
manipulation.
• What do you meant by static and dynamic modeling?
Static modeling is used to specify structure of the objects that exist in the problem
domain. These are expressed using class, object and USECASE diagrams.
But Dynamic modeling refers representing the object interactions during runtime.
It is represented by sequence, activity, collaboration and statechart diagrams.
• Why generalization is very strong?
Even though Generalization satisfies Structural, Interface, Behaviour properties. It is
mathematically very strong, as it is Antisymmetric and Transitive.
Antisymmetric: employee is a person, but not all persons are employees.
Mathematically all As’ are B, but all Bs’ not A.
Transitive: A=>B, B=>c then A=>c.
A. Salesman.
B. Employee.
C. Person.
Note: All the other relationships satisfy all the properties like Structural
properties, Interface properties, Behavior properties.

• Differentiate Aggregation and containment?


Aggregation is the relationship between the whole and a part. We can add/subtract some
properties in the part (slave) side. It won't affect the whole part.
Best example is Car, which contains the wheels and some extra parts. Even
though the parts are not there we can call it as car.
But, in the case of containment the whole part is affected when the part within
that got affected. The human body is an apt example for this relationship. When the
whole body dies the parts (heart etc) are died.

• Can link and Association applied interchangeably?


No, You cannot apply the link and Association interchangeably. Since link is used
represent the relationship between the two objects.
But Association is used represent the relationship between the two classes.
link :: student:Abhilash course:MCA
Association:: student course
• what is meant by "method-wars"?
Before 1994 there were different methodologies like Rumbaugh, Booch, Jacobson,
Meyer etc who followed their own notations to model the systems. The developers were
in a dilemma to choose the method which best accomplishes their needs. This
particular span was called as "method-wars"
• Whether unified method and unified modeling language are same or different?
Unified method is convergence of the Rumbaugh and Booch.
Unified modeling lang. is the fusion of Rumbaugh, Booch and Jacobson as well as
Betrand Meyer (whose contribution is "sequence diagram"). Its' the superset of all the
methodologies.
• Who were the three famous amigos and what was their contribution to the object
community?
The Three amigos namely,
Ø James Rumbaugh (OMT): A veteran in analysis who came up with an idea about the
objects and their Relationships (in particular Associations).
Ø Grady Booch: A veteran in design who came up with an idea about partitioning of
systems into subsystems.

Ø Ivar Jacobson (Objectory): The father of USECASES, who described about the user
and system interaction.
• Why does the function arguments are called as "signatures"?
The arguments distinguish functions with the same name (functional
polymorphism). The name alone does not necessarily identify a unique function.
However, the name and its arguments (signatures) will uniquely identify a function.
In real life we see suppose, in class there are two guys with same name, but they
can be easily identified by their signatures. The same concept is applied here.
ex:
class person
{
public:
char getsex();
void setsex(char);
void setsex(int);
};
In the above example we see that there is a function setsex() with same name but
with different signature.

Base class has some virtual method and derived class has a method with the same name. If we
initialize the base class pointer with derived object, calling of that virtual method will result in
which method being called?
a. Base method
b. Derived method..

Ans. b

For the following C program


#define AREA(x)(3.14*x*x)
main()
{float r1=6.25,r2=2.5,a;
a=AREA(r1);
printf("\n Area of the circle is %f", a);
a=AREA(r2);
printf("\n Area of the circle is %f", a);
}
What is the output?
Ans. Area of the circle is 122.656250
Area of the circle is 19.625000

void main()
{
int d=5;
printf("%f",d);
}

Ans: Undefined

void main()
{
int i;
for(i=1;i<4,i++)
switch(i)
case 1: printf("%d",i);break;
{
case 2:printf("%d",i);break;
case 3:printf("%d",i);break;
}
switch(i) case 4:printf("%d",i);
}

Ans: 1,2,3,4

void main()
{
char *s="\12345s\n";
printf("%d",sizeof(s));
}

Ans: 6

void main()
{
unsigned i=1; /* unsigned char k= -1 => k=255; */
signed j=-1; /* char k= -1 => k=65535 */
/* unsigned or signed int k= -1 =>k=65535 */
if(i
printf("less");
else
if(i>j)
printf("greater");
else
if(i==j)
printf("equal");
}

Ans: less

void main()
{
float j;
j=1000*1000;
printf("%f",j);
}

1. 1000000
2. Overflow
3. Error
4. None

Ans: 4

How do you declare an array of N pointers to functions returning pointers to functions returning
pointers to characters?

Ans: The first part of this question can be answered in at least


three ways:

1. char *(*(*a[N])())();

2. Build the declaration up incrementally, using typedefs:

typedef char *pc; /* pointer to char */


typedef pc fpc(); /* function returning pointer to char */
typedef fpc *pfpc; /* pointer to above */
typedef pfpc fpfpc(); /* function returning... */
typedef fpfpc *pfpfpc; /* pointer to... */
pfpfpc a[N]; /* array of... */

3. Use the cdecl program, which turns English into C and vice
versa:

cdecl> declare a as array of pointer to function returning


pointer to function returning pointer to char
char *(*(*a[])())()

cdecl can also explain complicated declarations, help with


casts, and indicate which set of parentheses the arguments
go in (for complicated function definitions, like the one
above).
Any good book on C should explain how to read these complicated
C declarations "inside out" to understand them ("declaration
mimics use").
The pointer-to-function declarations in the examples above have
not included parameter type information. When the parameters
have complicated types, declarations can *really* get messy.
(Modern versions of cdecl can help here, too.)

What are the number of syntax errors ?


int f()
void main()
{
f(1);
f(1,2);
f(1,2,3);
}
f(int i,int j,int k)
{
printf("%d %d %d",i,j,k);
}

Ans: None.

void main()
{
int i=7;
printf("%d",i++*i++);
}

Ans: 56

#define one 0
#ifdef one
printf("one is defined ");
#ifndef one
printf("one is not defined ");

Ans: "one is defined"

void main()
{
int count=10,*temp,sum=0;
temp=&count;
*temp=20;
temp=∑
*temp=count;
printf("%d %d %d ",count,*temp,sum);
}

Ans: 20 20 20

What is alloca()
Ans : It allocates and frees memory after use/after getting out of scope

main()
{
static i=3;
printf("%d",i--);
return i>0 ? main():0;
}

Ans: 321

char *foo()
{
char result[100]);
strcpy(result,"anything is good");
return(result);
}
void main()
{
char *j;
j=foo()
printf("%s",j);
}

Ans: anything is good.

void main()
{
char *s[]={ "dharma","hewlett-packard","siemens","ibm"};
char **p;
p=s;
printf("%s",++*p);
printf("%s",*p++);
printf("%s",++*p);
}

Ans: "harma" (p->add(dharma) && (*p)->harma)


"harma" (after printing, p->add(hewlett-packard) &&(*p)->harma)
"ewlett-packard"
Output of the following program is
main()
{int i=0;
for(i=0;i<20;i++)
{switch(i)
case 0:i+=5;
case 1:i+=2;
case 5:i+=5;
default i+=4;
break;}
printf("%d,",i);
}
}

a) 0,5,9,13,17
b) 5,9,13,17
c) 12,17,22
d) 16,21
e) Syntax error

Ans. (d)

What is the ouptut in the following program


main()
{char c=-64;
int i=-32
unsigned int u =-16;
if(c>i)
{printf("pass1,");
if(c
printf("pass2");
else
printf("Fail2");
}
else
printf("Fail1);
if(i
printf("pass2");
else
printf("Fail2")
}

a) Pass1,Pass2
b) Pass1,Fail2
c) Fail1,Pass2
d) Fail1,Fail2
e) None of these

Ans. (c)

What will the following program do?


void main()
{
int i;
char a[]="String";
char *p="New Sring";
char *Temp;
Temp=a;
a=malloc(strlen(p) + 1);
strcpy(a,p); //Line number:9//
p = malloc(strlen(Temp) + 1);
strcpy(p,Temp);
printf("(%s, %s)",a,p);
free(p);
free(a);
} //Line number 15//

a) Swap contents of p & a and print:(New string, string)


b) Generate compilation error in line number 8
c) Generate compilation error in line number 5
d) Generate compilation error in line number 7
e) Generate compilation error in line number 1

Ans. (b)

In the following code segment what will be the result of the function,
value of x , value of y
{unsigned int x=-1;
int y;
y = ~0;
if(x == y)
printf("same");
else
printf("not same");
}

a) same, MAXINT, -1
b) not same, MAXINT, -MAXINT
c) same , MAXUNIT, -1
d) same, MAXUNIT, MAXUNIT
e) not same, MAXINT, MAXUNIT

Ans. (a)

What will be the result of the following program ?


char *gxxx()
{static char xxx[1024];
return xxx;
}
main()
{char *g="string";
strcpy(gxxx(),g);
g = gxxx();
strcpy(g,"oldstring");
printf("The string is : %s",gxxx());
}

a) The string is : string


b) The string is :Oldstring
c) Run time error/Core dump
d) Syntax error during compilation
e) None of these

Ans. (b)

Find the output for the following C program


main()
{
char *p1="Name";
char *p2;
p2=(char *)malloc(20);
while(*p2++=*p1++);
printf("%s\n",p2);
}

Ans. An empty string

Find the output for the following C program


main()
{
int x=20,y=35;
x = y++ + x++;
y = ++y + ++x;
printf("%d %d\n",x,y);
}
Ans. 57 94

Find the output for the following C program


main()
{
int x=5;
printf("%d %d %d\n",x,x<<2,x>>2);
}

Ans. 5 20 1

Find the output for the following C program


#define swap1(a,b) a=a+b;b=a-b;a=a-b;
main()
{
int x=5,y=10;
swap1(x,y);
printf("%d %d\n",x,y);
swap2(x,y);
printf("%d %d\n",x,y);
}
int swap2(int a,int b)
{
int temp;
temp=a;
b=a;
a=temp;
return;
}

Ans. 10 5

Find the output for the following C program


main()
{
char *ptr = "Ramco Systems";
(*ptr)++;
printf("%s\n",ptr);
ptr++;
printf("%s\n",ptr);
}

Ans. Samco Systems


Find the output for the following C program
#include
main()
{
char s1[]="Ramco";
char s2[]="Systems";
s1=s2;
printf("%s",s1);
}

Ans. Compilation error giving it cannot be an modifiable 'lvalue'

Find the output for the following C program


#include
main()
{
char *p1;
char *p2;
p1=(char *) malloc(25);
p2=(char *) malloc(25);
strcpy(p1,"Ramco");
strcpy(p2,"Systems");
strcat(p1,p2);
printf("%s",p1);
}

Ans. RamcoSystems

Find the output for the following C program


# define TRUE 0
some code
while(TRUE)
{
some code
}

Ans. This won't go into the loop as TRUE is defined as 0

struct list{
int x;
struct list *next;
}*head;

the struct head.x =100

Is the above assignment to pointer is correct or wrong ?


Ans. Wrong

What is the output of the following ?

int i;
i=1;
i=i+2*i++;
printf(%d,i);

Ans. 4

FILE *fp1,*fp2;

fp1=fopen("one","w")
fp2=fopen("one","w")
fputc('A',fp1)
fputc('B',fp2)
fclose(fp1)
fclose(fp2)
}

Find the Error, If Any?

Ans. no error. But It will over writes on same file.

What are the output(s) for the following ?


#define MAN(x,y) (x)>(y)?(x):(y)
{int i=10;
j=5;
k=0;
k=MAX(i++,++j);
printf(%d %d %d %d,i,j,k);
}

Ans. 10 5 0

void main()
{
int i=7;
printf("%d",i++*i++);
}

Ans: 56
C++ Questions

Note : All the programs are tested under Turbo C++ 3.0, 4.5 and Microsoft VC++ 6.0 compilers.

It is assumed that,

 Programs run under Windows environment,


 The underlying machine is an x86 based system,
 Program is compiled using Turbo C/C++ compiler.
The program output may depend on the information based on this assumptions (for
example sizeof(int) == 2 may be assumed).

1) class Sample

public:

int *ptr;

Sample(int i)

ptr = new int(i);

~Sample()

delete ptr;

void PrintVal()

cout << "The value is " << *ptr;

};
void SomeFunc(Sample x)

cout << "Say i am in someFunc " << endl;

int main()

Sample s1= 10;

SomeFunc(s1);

s1.PrintVal();

Answer:

Say i am in someFunc

Null pointer assignment(Run-time error)

Explanation:

As the object is passed by value to SomeFunc the destructor of the object is called when
the control returns from the function. So when PrintVal is called it meets up with ptr that has
been freed.The solution is to pass the Sample object by reference to SomeFunc:

void SomeFunc(Sample &x)

cout << "Say i am in someFunc " << endl;

because when we pass objects by refernece that object is not destroyed. while returning from the

function.
2) Which is the parameter that is added to every non-static member function when it is called?
Answer:

‘this’ pointer

3) class base

public:

int bval;

base(){ bval=0;}

};

class deri:public base

public:

int dval;

deri(){ dval=1;}

};

void SomeFunc(base *arr,int size)

for(int i=0; i<size; i++,arr++)

cout<<arr->bval;

cout<<endl;

int main()

{
base BaseArr[5];

SomeFunc(BaseArr,5);

deri DeriArr[5];

SomeFunc(DeriArr,5);

Answer:

00000

01010

Explanation:

The function SomeFunc expects two arguments.The first one is a pointer to an array of
base class objects and the second one is the sizeof the array.The first call of someFunc calls it
with an array of bae objects, so it works correctly and prints the bval of all the objects. When
Somefunc is called the second time the argument passed is the pointeer to an array of derived
class objects and not the array of base class objects. But that is what the function expects to be
sent. So the derived class pointer is promoted to base class pointer and the address is sent to the
function. SomeFunc() knows nothing about this and just treats the pointer as an array of base
class objects. So when arr++ is met, the size of base class object is taken into consideration and
is incremented by sizeof(int) bytes for bval (the deri class objects have bval and dval as members
and so is of size >= sizeof(int)+sizeof(int) ).

4) class base

public:

void baseFun(){ cout<<"from base"<<endl;}

};

class deri:public base

public:
void baseFun(){ cout<< "from derived"<<endl;}

};

void SomeFunc(base *baseObj)

baseObj->baseFun();

int main()

base baseObject;

SomeFunc(&baseObject);

deri deriObject;

SomeFunc(&deriObject);

Answer:

from base

from base

Explanation:

As we have seen in the previous case, SomeFunc expects a pointer to a base class. Since
a pointer to a derived class object is passed, it treats the argument only as a base class pointer and
the corresponding base function is called.

5) class base

public:

virtual void baseFun(){ cout<<"from base"<<endl;}

};
class deri:public base

public:

void baseFun(){ cout<< "from derived"<<endl;}

};

void SomeFunc(base *baseObj)

baseObj->baseFun();

int main()

base baseObject;

SomeFunc(&baseObject);

deri deriObject;

SomeFunc(&deriObject);

Answer:

from base

from derived

Explanation:

Remember that baseFunc is a virtual function. That means that it supports run-time
polymorphism. So the function corresponding to the derived class object is called.

void main()
{
int a, *pa, &ra;
pa = &a;
ra = a;
cout <<"a="<<a <<"*pa="<<*pa <<"ra"<<ra ;
}
/*
Answer :
Compiler Error: 'ra',reference must be initialized
Explanation :
Pointers are different from references. One of the main
differences is that the pointers can be both initialized and assigned,
whereas references can only be initialized. So this code issues an error.
*/

const int size = 5;


void print(int *ptr)
{
cout<<ptr[0];
}

void print(int ptr[size])


{
cout<<ptr[0];
}

void main()
{
int a[size] = {1,2,3,4,5};
int *b = new int(size);
print(a);
print(b);
}
/*
Answer:
Compiler Error : function 'void print(int *)' already has a body

Explanation:
Arrays cannot be passed to functions, only pointers (for arrays, base addresses)
can be passed. So the arguments int *ptr and int prt[size] have no difference
as function arguments. In other words, both the functoins have the same signature and
so cannot be overloaded.
*/

class some{
public:
~some()
{
cout<<"some's destructor"<<endl;
}
};

void main()
{
some s;
s.~some();
}
/*
Answer:
some's destructor
some's destructor
Explanation:
Destructors can be called explicitly. Here 's.~some()' explicitly calls the
destructor of 's'. When main() returns, destructor of s is called again,
hence the result.
*/

#include <iostream.h>

class fig2d
{
int dim1;
int dim2;

public:
fig2d() { dim1=5; dim2=6;}

virtual void operator<<(ostream & rhs);


};

void fig2d::operator<<(ostream &rhs)


{
rhs <<this->dim1<<" "<<this->dim2<<" ";
}

/*class fig3d : public fig2d


{
int dim3;
public:
fig3d() { dim3=7;}
virtual void operator<<(ostream &rhs);
};
void fig3d::operator<<(ostream &rhs)
{
fig2d::operator <<(rhs);
rhs<<this->dim3;
}
*/

void main()
{
fig2d obj1;
// fig3d obj2;

obj1 << cout;


// obj2 << cout;
}
/*
Answer :
56
Explanation:
In this program, the << operator is overloaded with ostream as argument.
This enables the 'cout' to be present at the right-hand-side. Normally, 'cout'
is implemented as global function, but it doesn't mean that 'cout' is not possible
to be overloaded as member function.
Overloading << as virtual member function becomes handy when the class in which
it is overloaded is inherited, and this becomes available to be overrided. This is as opposed
to global friend functions, where friend's are not inherited.
*/

class opOverload{
public:
bool operator==(opOverload temp);
};

bool opOverload::operator==(opOverload temp){


if(*this == temp ){
cout<<"The both are same objects\n";
return true;
}
else{
cout<<"The both are different\n";
return false;
}
}

void main(){
opOverload a1, a2;
a1= =a2;
}

Answer :
Runtime Error: Stack Overflow
Explanation :
Just like normal functions, operator functions can be called recursively. This program just
illustrates that point, by calling the operator == function recursively, leading to an infinite loop.

class complex{
double re;
double im;
public:
complex() : re(1),im(0.5) {}
bool operator==(complex &rhs);
operator int(){}
};

bool complex::operator == (complex &rhs){


if((this->re == rhs.re) && (this->im == rhs.im))
return true;
else
return false;
}

int main(){
complex c1;
cout<< c1;
}

Answer : Garbage value

Explanation:
The programmer wishes to print the complex object using output
re-direction operator,which he has not defined for his lass.But the compiler instead of giving an
error sees the conversion function
and converts the user defined object to standard object and prints
some garbage value.

class complex{
double re;
double im;
public:
complex() : re(0),im(0) {}
complex(double n) { re=n,im=n;};
complex(int m,int n) { re=m,im=n;}
void print() { cout<<re; cout<<im;}
};

void main(){
complex c3;
double i=5;
c3 = i;
c3.print();
}

Answer:
5,5
Explanation:
Though no operator= function taking complex, double is defined, the double on the rhs is
converted into a temporary object using the single argument constructor taking double and
assigned to the lvalue.

void main()
{
int a, *pa, &ra;
pa = &a;
ra = a;
cout <<"a="<<a <<"*pa="<<*pa <<"ra"<<ra ;
}

Answer :
Compiler Error: 'ra',reference must be initialized
Explanation :
Pointers are different from references. One of the main
differences is that the pointers can be both initialized and assigned,
whereas references can only be initialized. So this code issues an error.

Try it Yourself

1) Determine the output of the 'C++' Codelet.

class base

public :
out()

cout<<"base ";

};

class deri{

public : out()

cout<<"deri ";

};

void main()

{ deri dp[3];

base *bp = (base*)dp;

for (int i=0; i<3;i++)

(bp++)->out();

2) Justify the use of virtual constructors and destructors in C++.

3) Each C++ object possesses the 4 member fns,(which can be declared by the programmer
explicitly or by the implementation if they are not available). What are those 4 functions?

4) What is wrong with this class declaration?


class something

char *str;
public:

something(){

st = new char[10]; }

~something()

delete str;

};

5) Inheritance is also known as -------- relationship. Containership as ________ relationship.

6) When is it necessary to use member-wise initialization list (also known as header


initialization list) in C++?

7) Which is the only operator in C++ which can be overloaded but NOT inherited.

8) Is there anything wrong with this C++ class declaration?

class temp

int value1;

mutable int value2;

public :

void fun(int val)

const{

((temp*) this)->value1 = 10;


value2 = 10;

};
1. What is a modifier?

Answer:

A modifier, also called a modifying function is a member function that changes the value
of at least one data member. In other words, an operation that modifies the state of an object.
Modifiers are also known as ‘mutators’.

2. What is an accessor?

Answer:

An accessor is a class operation that does not modify the state of an object. The accessor
functions need to be declared as const operations

3. Differentiate between a template class and class template.

Answer:

Template class:

A generic definition or a parameterized class not instantiated until the client provides the
needed information. It’s jargon for plain templates.

Class template:

A class template specifies how individual classes can be constructed much like the way a
class specifies how individual objects can be constructed. It’s jargon for plain classes.

4. When does a name clash occur?

Answer:

A name clash occurs when a name is defined in more than one place. For example., two
different class libraries could give two different classes the same name. If you try to use many
class libraries at the same time, there is a fair chance that you will be unable to compile or link
the program because of name clashes.

5. Define namespace.
Answer:

It is a feature in c++ to minimize name collisions in the global name space. This
namespace keyword assigns a distinct name to a library that allows other libraries to use the
same identifier names without creating any name collisions. Furthermore, the compiler uses the
namespace signature for differentiating the definitions.

6. What is the use of ‘using’ declaration.

Answer:

A using declaration makes it possible to use a name from a namespace without the scope
operator.

7. What is an Iterator class?

Answer:

A class that is used to traverse through the objects maintained by a container class. There
are five categories of iterators:

 input iterators,
 output iterators,
 forward iterators,
 bidirectional iterators,
 random access.
An iterator is an entity that gives access to the contents of a container object without
violating encapsulation constraints. Access to the contents is granted on a one-at-a-time basis in
order. The order can be storage order (as in lists and queues) or some arbitrary order (as in array
indices) or according to some ordering relation (as in an ordered binary tree). The iterator is a
construct, which provides an interface that, when called, yields either the next element in the
container, or some value denoting the fact that there are no more elements to examine. Iterators
hide the details of access to and update of the elements of a container class.

The simplest and safest iterators are those that permit read-only access to the contents of
a container class. The following code fragment shows how an iterator might appear in code:

cont_iter:=new cont_iterator();

x:=cont_iter.next();

while x/=none do
...

s(x);

...

x:=cont_iter.next();

end;

In this example, cont_iter is the name of the iterator. It is created on the first line by
instantiation of cont_iterator class, an iterator class defined to iterate over some container class,
cont. Succesive elements from the container are carried to x. The loop terminates when x is
bound to some empty value. (Here, none)In the middle of the loop, there is s(x) an operation on
x, the current element from the container. The next element of the container is obtained at the
bottom of the loop.

9. List out some of the OODBMS available.

Answer:

 GEMSTONE/OPAL of Gemstone systems.


 ONTOS of Ontos.
 Objectivity of Objectivity inc.
 Versant of Versant object technology.
 Object store of Object Design.
 ARDENT of ARDENT software.
 POET of POET software.

10. List out some of the object-oriented methodologies.

Answer:

 Object Oriented Development (OOD) (Booch 1991,1994).


 Object Oriented Analysis and Design (OOA/D) (Coad and Yourdon 1991).
 Object Modelling Techniques (OMT) (Rumbaugh 1991).
 Object Oriented Software Engineering (Objectory) (Jacobson 1992).
 Object Oriented Analysis (OOA) (Shlaer and Mellor 1992).
 The Fusion Method (Coleman 1991).

11. What is an incomplete type?


Answer:

Incomplete types refers to pointers in which there is non availability of the


implementation of the referenced location or it points to some location whose value is not
available for modification.

Example:

int *i=0x400 // i points to address 400

*i=0; //set the value of memory location pointed by i.

Incomplete types are otherwise called uninitialized pointers.

12. What is a dangling pointer?

Answer:

A dangling pointer arises when you use the address of an object after its lifetime is over.

This may occur in situations like returning addresses of the automatic variables from a function
or using the address of the memory block after it is freed.

13. Differentiate between the message and method.

Answer:

Message Method

Objects communicate by sending messages Provides response to a message.

to each other.

A message is sent to invoke a method. It is an implementation of an operation.

14. What is an adaptor class or Wrapper class?

Answer:

A class that has no functionality of its own. Its member functions hide the use of a third
party software component or an object with the non-compatible interface or a non- object-
oriented implementation.
15. What is a Null object?

Answer:

It is an object of some class whose purpose is to indicate that a real object of that class
does not exist. One common use for a null object is a return value from a member function that is
supposed to return an object with some specified properties but cannot find such an object.

16. What is class invariant?

Answer:

A class invariant is a condition that defines all valid states for an object. It is a logical
condition to ensure the correct working of a class. Class invariants must hold when an object is
created, and they must be preserved under all operations of the class. In particular all class
invariants are both preconditions and post-conditions for all operations or member functions of
the class.

17. What do you mean by Stack unwinding?

Answer:

It is a process during exception handling when the destructor is called for all local objects
between the place where the exception was thrown and where it is caught.

18. Define precondition and post-condition to a member function.

Answer:

Precondition:

A precondition is a condition that must be true on entry to a member function. A class is


used correctly if preconditions are never false. An operation is not responsible for doing anything
sensible if its precondition fails to hold.

For example, the interface invariants of stack class say nothing about pushing yet another
element on a stack that is already full. We say that isful() is a precondition of the push operation.
Post-condition:

A post-condition is a condition that must be true on exit from a member function if the
precondition was valid on entry to that function. A class is implemented correctly if post-
conditions are never false.

For example, after pushing an element on the stack, we know that isempty() must
necessarily hold. This is a post-condition of the push operation.

19. What are the conditions that have to be met for a condition to be an invariant of the class?

Answer:

 The condition should hold at the end of every constructor.


 The condition should hold at the end of every mutator(non-const) operation.

20. What are proxy objects?

Answer:

Objects that stand for other objects are called proxy objects or surrogates.

Example:

template<class T>

class Array2D

public:

class Array1D

public:

T& operator[] (int index);

const T& operator[] (int index) const;

...
};

Array1D operator[] (int index);

const Array1D operator[] (int index) const;

...

};

The following then becomes legal:

Array2D<float>data(10,20);

........

cout<<data[3][6]; // fine

Here data[3] yields an Array1D object and the operator [] invocation on that object yields
the float in position(3,6) of the original two dimensional array. Clients of the Array2D class need
not be aware of the presence of the Array1D class. Objects of this latter class stand for one-
dimensional array objects that, conceptually, do not exist for clients of Array2D. Such clients
program as if they were using real, live, two-dimensional arrays. Each Array1D object stands for
a one-dimensional array that is absent from a conceptual model used by the clients of Array2D.
In the above example, Array1D is a proxy class. Its instances stand for one-dimensional arrays
that, conceptually, do not exist.

21. Name some pure object oriented languages.

Answer:

 Smalltalk,
 Java,
 Eiffel,
 Sather.

22. Name the operators that cannot be overloaded.

Answer:
sizeof . .* .-> :: ?:

23. What is a node class?

Answer:

A node class is a class that,

 relies on the base class for services and implementation,


 provides a wider interface to te users than its base class,
 relies primarily on virtual functions in its public interface
 depends on all its direct and indirect base class
 can be understood only in the context of the base class
 can be used as base for further derivation
 can be used to create objects.
A node class is a class that has added new services or functionality beyond the services inherited
from its base class.

24. What is an orthogonal base class?

Answer:

If two base classes have no overlapping methods or data they are said to be independent

of, or orthogonal to each other. Orthogonal in the sense means that two classes operate in

different dimensions and do not interfere with each other in any way. The same derived class

may inherit such classes with no difficulty.

25. What is a container class? What are the types of container classes?

Answer:

A container class is a class that is used to hold objects in memory or external storage. A
container class acts as a generic holder. A container class has a predefined behavior and a well-
known interface. A container class is a supporting class whose purpose is to hide the topology
used for maintaining the list of objects in memory. When a container class contains a group of
mixed objects, the container is called a heterogeneous container; when the container is holding a
group of objects that are all the same, the container is called a homogeneous container.
26. What is a protocol class?

Answer:

An abstract class is a protocol class if:

 it neither contains nor inherits from classes that contain member data, non-virtual
functions, or private (or protected) members of any kind.
 it has a non-inline virtual destructor defined with an empty implementation,
 all member functions other than the destructor including inherited functions, are
declared pure virtual functions and left undefined.

27. What is a mixin class?

Answer:

A class that provides some but not all of the implementation for a virtual base class is
often called mixin. Derivation done just for the purpose of redefining the virtual functions in the
base classes is often called mixin inheritance. Mixin classes typically don't share common bases.

28. What is a concrete class?

Answer:

A concrete class is used to define a useful object that can be instantiated as an automatic
variable on the program stack. The implementation of a concrete class is defined. The concrete
class is not intended to be a base class and no attempt to minimize dependency on other classes
in the implementation or behavior of the class.

29.What is the handle class?

Answer:

A handle is a class that maintains a pointer to an object that is programmatically


accessible through the public interface of the handle class.

Explanation:

In case of abstract classes, unless one manipulates the objects of these classes through
pointers and references, the benefits of the virtual functions are lost. User code may become
dependent on details of implementation classes because an abstract type cannot be allocated
statistically or on the stack without its size being known. Using pointers or references implies
that the burden of memory management falls on the user. Another limitation of abstract class
object is of fixed size. Classes however are used to represent concepts that require varying
amounts of storage to implement them.
A popular technique for dealing with these issues is to separate what is used as a single object in
two parts: a handle providing the user interface and a representation holding all or most of the
object's state. The connection between the handle and the representation is typically a pointer in
the handle. Often, handles have a bit more data than the simple representation pointer, but not
much more. Hence the layout of the handle is typically stable, even when the representation
changes and also that handles are small enough to move around relatively freely so that the user
needn’t use the pointers and the references.

30. What is an action class?

Answer:

The simplest and most obvious way to specify an action in C++ is to write a function.
However, if the action has to be delayed, has to be transmitted 'elsewhere' before being
performed, requires its own data, has to be combined with other actions, etc then it often
becomes attractive to provide the action in the form of a class that can execute the desired action
and provide other services as well. Manipulators used with iostreams is an obvious example.

Explanation:

A common form of action class is a simple class containing just one virtual function.

class Action

public:

virtual int do_it( int )=0;

virtual ~Action( );

}
Given this, we can write code say a member that can store actions for later execution

without using pointers to functions, without knowing anything about the objects involved, and

without even knowing the name of the operation it invokes. For example:

class write_file : public Action

File& f;

public:

int do_it(int)

return fwrite( ).suceed( );

};

class error_message: public Action

response_box db(message.cstr( ),"Continue","Cancel","Retry");

switch (db.getresponse( ))

case 0: return 0;

case 1: abort();

case 2: current_operation.redo( );return 1;

};

A user of the Action class will be completely isolated from any knowledge of derived classes

such as write_file and error_message.


31. When can you tell that a memory leak will occur?

Answer:

A memory leak occurs when a program loses the ability to free a block of dynamically
allocated memory.

32.What is a parameterized type?

Answer:

A template is a parameterized construct or type containing generic code that can use or
manipulate any type. It is called parameterized because an actual type is a parameter of the code
body. Polymorphism may be achieved through parameterized types. This type of polymorphism
is called parameteric polymorphism. Parameteric polymorphism is the mechanism by which the
same code is used on different types passed as parameters.

33. Differentiate between a deep copy and a shallow copy?

Answer:

Deep copy involves using the contents of one object to create another instance of the
same class. In a deep copy, the two objects may contain ht same information but the target object
will have its own buffers and resources. the destruction of either object will not affect the
remaining object. The overloaded assignment operator would create a deep copy of objects.

Shallow copy involves copying the contents of one object into another instance of the
same class thus creating a mirror image. Owing to straight copying of references and pointers,
the two objects will share the same externally contained contents of the other object to be
unpredictable.

Explanation:

Using a copy constructor we simply copy the data values member by member. This
method of copying is called shallow copy. If the object is a simple class, comprised of built in
types and no pointers this would be acceptable. This function would use the values and the
objects and its behavior would not be altered with a shallow copy, only the addresses of pointers
that are members are copied and not the value the address is pointing to. The data values of the
object would then be inadvertently altered by the function. When the function goes out of scope,
the copy of the object with all its data is popped off the stack.
If the object has any pointers a deep copy needs to be executed. With the deep copy of an
object, memory is allocated for the object in free store and the elements pointed to are copied. A
deep copy is used for objects that are returned from a function.

34. What is an opaque pointer?

Answer:

A pointer is said to be opaque if the definition of the type to which it points to is not
included in the current translation unit. A translation unit is the result of merging an
implementation file with all its headers and header files.

35. What is a smart pointer?

Answer:

A smart pointer is an object that acts, looks and feels like a normal pointer but offers
more functionality. In C++, smart pointers are implemented as template classes that encapsulate
a pointer and override standard pointer operators. They have a number of advantages over
regular pointers. They are guaranteed to be initialized as either null pointers or pointers to a heap
object. Indirection through a null pointer is checked. No delete is ever necessary. Objects are
automatically freed when the last pointer to them has gone away. One significant problem with
these smart pointers is that unlike regular pointers, they don't respect inheritance. Smart pointers
are unattractive for polymorphic code. Given below is an example for the implementation of
smart pointers.

Example:

template <class X>

class smart_pointer

public:

smart_pointer(); // makes a null pointer

smart_pointer(const X& x) // makes pointer to copy of x

X& operator *( );
const X& operator*( ) const;

X* operator->() const;

smart_pointer(const smart_pointer <X> &);

const smart_pointer <X> & operator =(const smart_pointer<X>&);

~smart_pointer();

private:

//...

};

This class implement a smart pointer to an object of type X. The object itself is located on
the heap. Here is how to use it:

smart_pointer <employee> p= employee("Harris",1333);

Like other overloaded operators, p will behave like a regular pointer,

cout<<*p;

p->raise_salary(0.5);

36. What is reflexive association?

Answer:

The 'is-a' is called a reflexive association because the reflexive association permits
classes to bear the is-a association not only with their super-classes but also with themselves. It
differs from a 'specializes-from' as 'specializes-from' is usually used to describe the association
between a super-class and a sub-class. For example:

Printer is-a printer.

37. What is slicing?

Answer:
Slicing means that the data added by a subclass are discarded when an object of the
subclass is passed or returned by value or from a function expecting a base class object.

Explanation:

Consider the following class declaration:

class base

...

base& operator =(const base&);

base (const base&);

void fun( )

base e=m;

e=m;

As base copy functions don't know anything about the derived only the base part of the
derived is copied. This is commonly referred to as slicing. One reason to pass objects of classes
in a hierarchy is to avoid slicing. Other reasons are to preserve polymorphic behavior and to gain
efficiency.

38. What is name mangling?

Answer:

Name mangling is the process through which your c++ compilers give each function in your

program a unique name. In C++, all programs have at-least a few functions with the same

name. Name mangling is a concession to the fact that linker always insists on all function

names being unique.


Example:

In general, member names are made unique by concatenating the name of the member
with that of the class e.g. given the declaration:

class Bar

public:

int ival;

...

};

ival becomes something like:

// a possible member name mangling

ival__3Bar

Consider this derivation:

class Foo : public Bar

public:

int ival;

...

The internal representation of a Foo object is the concatenation of its base and derived class

members.

// Pseudo C++ code

// Internal representation of Foo

class Foo

{
public:

int ival__3Bar;

int ival__3Foo;

...

};

Unambiguous access of either ival members is achieved through name mangling. Member

functions, because they can be overloaded, require an extensive mangling to provide each

with a unique name. Here the compiler generates the same name for the two overloaded

instances(Their argument lists make their instances unique).

39. What are proxy objects?

Answer:

Objects that points to other objects are called proxy objects or surrogates. Its an object
that provides the same interface as its server object but does not have any functionality. During a
method invocation, it routes data to the true server object and sends back the return value to the
object.

40. Differentiate between declaration and definition in C++.

Answer:

A declaration introduces a name into the program; a definition provides a unique description

of an entity (e.g. type, instance, and function). Declarations can be repeated in a given scope,

it introduces a name in a given scope. There must be exactly one definition of every object,

function or class used in a C++ program.

A declaration is a definition unless:

 it declares a function without specifying its body,


 it contains an extern specifier and no initializer or function body,
 it is the declaration of a static class data member without a class definition,
 it is a class name definition,
 it is a typedef declaration.
A definition is a declaration unless:

 it defines a static class data member,


 it defines a non-inline member function.

41. What is cloning?

Answer:

An object can carry out copying in two ways i.e. it can set itself to be a copy of another

object, or it can return a copy of itself. The latter process is called cloning.

42. Describe the main characteristics of static functions.

Answer:

The main characteristics of static functions include,

 It is without the a this pointer,


 It can't directly access the non-static members of its class
 It can't be declared const, volatile or virtual.
 It doesn't need to be invoked through an object of its class, although for
convenience, it may.

43. Will the inline function be compiled as the inline function always? Justify.

Answer:

An inline function is a request and not a command. Hence it won't be compiled as an


inline function always.

Explanation:

Inline-expansion could fail if the inline function contains loops, the address of an inline
function is used, or an inline function is called in a complex expression. The rules for inlining are
compiler dependent.
44. Define a way other than using the keyword inline to make a function inline.

Answer:

The function must be defined inside the class.

45. How can a '::' operator be used as unary operator?

Answer:

The scope operator can be used to refer to members of the global namespace. Because the
global namespace doesn’t have a name, the notation :: member-name refers to a member of the
global namespace. This can be useful for referring to members of global namespace whose
names have been hidden by names declared in nested local scope. Unless we specify to the
compiler in which namespace to search for a declaration, the compiler simple searches the
current scope, and any scopes in which the current scope is nested, to find the declaration for the
name.

46. What is placement new?

Answer:

When you want to call a constructor directly, you use the placement new. Sometimes you

have some raw memory that's already been allocated, and you need to construct an object in the

memory you have. Operator new's special version placement new allows you to do it.

class Widget

public :

Widget(int widgetsize);

...

Widget* Construct_widget_int_buffer(void *buffer,int widgetsize)

return new(buffer) Widget(widgetsize);


}

};

This function returns a pointer to a Widget object that's constructed within the buffer

passed to the function. Such a function might be useful for applications using shared memory or

memory-mapped I/O, because objects in such applications must be placed at specific addresses

or in memory allocated by special routines.

ANNEXURE 2 – CLASS TEST QUESTIONS:

What are the main characteristics of OOp Language?

What are the valid types of data that the main() can return in c/c++ Language

What are the difference between default and parameterized constructors?

List out the properties of a static member function

What are the functions supported by filestream classes for performing I/O operations?

What are the types of exceptions / C++ provides what type of exceptions.

Describe the advantages of OOP(8)

What are the differences between pointers to constants and constants pointers?

Describe the applications of OOP terminology

What is inline functions? Explain the situations where inline expansion may not work?

Explain copy constructor with suitable C++ coding

List out the rules for overloading oprators

Explain hybrid inheritance with suitable c++ coding

Define Polymorphism. Explain the different types of polymorphism

Write a c++ program to read from 2 files simultaneously.

Explain multiple catch statement with the help of suitable c++ coding.
What is object oriented paradigm?

What is the use of the scope resolution operator :: in c++?

What are the operators of c++ that can be overloaded?

How does constructor differ from normal functions?

What is the default access mode for class members?

What is an I/O stream?

Explain object oriented paradigm with all its essential elements

State the merits and demerits of object oriented methodology

Explain the following concepts of object oriented programming in detail with an example

Data abstracton

Inheritance

Polymorphism

Objects

Write a C++ program to extract the elements placed in the odd position of the array

State the rules to be followed while overloading an operator. Write a program to illustrate
overloading

Discuss about polymorphism and its advantages

Write a C++ program that will give the conditions of environment required, food habits and
unique characteristics of pet animals fish and dog. Define a base class called pet that describe
any common household pet; two derived classes called fish and dog with items specific to
that type of animal. Write pure virtual functions in the base class for operations that are
common to both types of animals. Write a program to test the usage of classes.

Explain the 4 functions Seekg, Seekp, tellg, tellp used for setting pointers during file
operation and show how they are derived from fstream class
Write a program to append to the contents of a file

Write a program to write the text in a file .Display the contents of file in reverse order.

What are the keywords used in c++ for exception handling?. Describe their usage with
suitable example

Discuss about various types of inheritance possible in c++

Give an example that fits the following inheritance hierarchy. Write a C++ program to
implement this.

List the different programming methodologies

What are the features of c++?

Distinguish between constructors and destructors.

What are the different access specifiers in c++?

Give the use of virtual functions

What is meant by multiple inheritance?

How exceptional handling is useful in c++?

List any four manipulators in c++

What is the difference between overloading and overriding?

Compare the different programming methodologies


Discuss the basic concepts of OOPS

Write a brief note on class with suitable example

Discuss in detail about the different types of constructors with suitable programming
examples.

Write a brief note on this pointer with suitable example.

Write a c++ program to illustrate the use of control statements

Write a c++ program to overload the insertion operator << and the extraction operator >>

Discuss briefly on friend functions

What is meant by an abstract base class? Explain the use of it with suitable programming
example.

Explain how the classes can be derived with suitable example

Write a c++ program using function template for finding the sum of the values in an array

Describe class templates in c++ with an example

Explain the following with suitable programming examples

File stream classes

Exception handling in c++


Answer all questions

PART-A

1. List any four object oriented programming concepts.

2. What is an abstract class ?

3. What is a copy constructor ?

4. What are the operators that cannot be overloaded ?

5. What are templates ?

6. Illustrate the exception handling mechanism.

7. What are the visibility mode in inheritance ?

8. What is the prototype of a typical pure virtual function ?


9. What are the file stream classes used for creating input and output files ?

10. List out any four containers supported by Standard Template Library ?

PART-B

11. (a) (i)Explain the idea of Classes, Data abstraction and encapsulation. (8)

(ii) Write a C++ program that inputs two numbers and outputs the largest number using class.(8)
(OR)
(b) (i)What are the rules to be followed in function overloading, (4)

(ii) Write a C++ program that takes either two integers or two floating point numbers and outputs the
smallest using class friend function and function overloading (12)

12. (a) (i)Explain the various types of constructors (4)

(ii)Write a C++ program that takes the (x,y) coordinates of two points and outputs the distance
between them using constructors. (12)
(OR)
(b) Write a C++ program to take two values of time(hr,min,sec) and output their sum using
constructor and operator overloading. (16)

13. (a) (i)Write the syntax for member function template. (4)

(ii)Write a C++ program using class templates for finding scalar product for int type vector and float
type vector. (12)
(OR)
(b) (i)Explain how rethrowing of an exception is done. (4)

(ii) Write a C++ program that illustrates multiple catch statements. (12)

14. (a) (i)Explain the different forms of inheritance. (4)

(ii)Write a C++ program handling the following details for students and staff using inheritance.
Student details: name,address,percentage_marks.
Staff details :name,address,salary.
Create appropriate base and derived class.Input the details and output them. (12)
(OR)
(b) (i)Explain the need for pure virtual functions. (4)

(ii)Write a C++ program for calculating the area of rectangle and circle using run time polymorphism.
(12)

15. (a) (i)Explain any two functions for manipulation file pointers. (4)

(ii)A data file "DATA" contains the name and marks of a set of students.Write a C++ program That
reads the contents of the this file into an object,sorts the data in descending order of the marks and
writes the result to an output file "OUTPUT". (12)
(OR)
(b) (i)Explain any two sequence containers supported by Standard Template Library. (4)

(ii)Write a C++ Program using lists from STL to input 10 numbers and store them in the list.From the
list create two more list one containing even numbers another containing odd numbers.Output all
three lists. (12)

------------------------------------------------------------------

OBJECT AND CLASSES


PART-A (2 MARKS)
1. Write any four features of OOPS.
2. Give any four applications of OOPS.
3. Define class and object.
4. What is a scope resolution operator?
5. What do you mean by enumerated data type?
6. What are symbolic constants?
7. What do you mean by dynamic initialization of variables?
8. What are reference variable?
9. What is member-dereferencing operator?
10. What is function prototype?
11. What is an inline function?
12. What is a default argument?
13. What are the constant arguments?
14. What is call- by- reference?
15. What is the significance of const pointer?
16. What is the significance of pointer to constant?
17. What are the advantages of using new and delete operator?
PART-B (16 MARKS)
1. i) Explain with the Basic Concepts of object oriented programming.
(8 Marks)
ii) Explain the use of constant pointers and pointers to constant with an
example. (8 Marks)
2. i) Difference between class and struct and also illustrate with an example.
(8 Marks)
ii) What are the difference between pointers to constants and constant
to pointers? (8 Marks)
3. i) Write a C++ program using inline function. (8 Marks)
ii)Write a C++ program to illustrate the static function. (8 Marks)
4. i) Explain briefly about function overloading with a suitable example.
(8 Marks)
ii)Discuss constant and volatile functions. (8 Marks)
5. i) What is linkage specification and also explain its need. (8 Marks)
ii)Explain about call-by-reference and return by reference
with program. (8 Marks)
6. Explain Nested classes and Local classes with an example. (16 Marks)

UNIT-II
CONSTRUCTORS AND OVERLOADING
PART-A (2MARKS)
1. Define constructor.
2. Define default constructor.
3. Define parameterized constructor.
4. Define default argument constructor.
5. What is the ambiguity between default constructor and default argument
constructor?
6. Define copy constructor.
7. Define dynamic constructor.
8. Define const object.
9. Define multiple constructors.
10. Write some special characteristics of constructor.
11. How the objects are initialized dynamically?
12. Define destructor.
13. What is operator overloading?
14. List some of the rules for operator overloading.
15. What are the conditions should a casting operator satisfy?
PART-B (16 MARKS)
1. Explain about Constructor and Destructor with suitable C++ coding.
(16 Marks)
2. Explain about Copy Constructor with an example. (16 Marks)
3. Explain Explicit Constructors, Parameterized Constructors and Multiple
constructors with suitable examples. (16 Marks)
4. How to achieve operator overloading through friend function? (16 Marks)
5. Write a program using friends function for overloading << and >>
operators. (16 Marks)
6. Explain wrapper classes with examples. (16 Marks)
UNIT-III
INHERITANCE AND POLYMORPHISM
PART-A (2MARKS)
1. What is polymorphism? What are its types?
2. What is meant by inheritance?
3. What is meant by Abstract base class?
4. What are the virtual functions?
5. What are pure virtual functions? Write the syntax.
6. Define ‘this’ pointer.
7. Define RTTI?
8. What is cross casting?
9. What is down casting?

PART-B (16 MARKS)


1. i) Explain the different types of polymorphism. (10 Marks)
ii) How to use RTTI for template objects? (6 Marks)
2. Explain various types of inheritance. (16 Marks)
3. Describe pure virtual function with an example. (16 Marks)
4. i) Write a C++ program using this pointer. (8 Marks)
ii) Write a C++ program using Dynamic const. (8 Marks)
5. Explain briefly about
a. Cross casting (8 Marks)
b. Down casting (8 Marks)
UNIT-IV
FILE MANIPULATION
PART-A (2MARKS)
1. What is the need for streams?
2. What are the input and output streams?
3. Classify the streams.
4. Difference between get (), put ().
5. How to open and close a file?
6. Write some file opening modes.
7. What is a file pointer?
8. What is command-line argument?
9. What is an error and error handling functions?
10. How will you create manipulators?
11. Write the syntax and use of getline () and write () functions.
PART-B (16 MARKS)
1. (a) What are streams? Why they are useful? (8 Marks)
(b) What is the importance of ios member flags in formatting IO? (8 Marks)
2. Explain about Formatted and Unformatted IO with suitable Example (16 Marks)
3. What is the manipulator? Differences between Manipulators and ios
Functions. (16 Marks)
4. Explain the process of open, read, write, and close files? (16 Marks)
5. Explain the roles of seekg (), seekp (), tellg (), tellp () functions in
the process of random access in a binary file. (16 Marks)
6. (a) How can we determine errors while dealing with files? (8 Marks)
(b) How can we open a text file and read from it? (4 Marks)
(c) How can we open a binary file and write to it? (4 Marks)
7. Explain about the STD Namespaces. (16Marks)
9. Explain the different constructions of string objects (16 Marks)
10. Explain the standard Template Library and how it is working? (16 Marks)

UNIT-V
TEMPLATES AND FILE HANDLING
PART- A (2 MARKS)
1. What is the need for template function in C++? What are their advantages?
2. What are the drawbacks of using macros?
3. What is the Instantiation?
4. What is Function Templates?
5. What is Class Templates?
6. What is Exception Handling?
7. What is generic programming?
8. What are the different mechanisms of traditional error handling?
9. What are Exceptions?
10. Define Try, Catch, and Throw.
11. What are the components of Exception Handling mechanism?
12. What is the Uncaught Exception?
13. What is the terminate () functions?
14. What are the disadvantages of the exception handling?
PART-B (16MARKS)
1. Explain the Function template. (16 Marks)
2. Explain the Class template. (16 Marks)
3. i) What is the need for Exceptional Handling (8 Marks)
ii) What are the components of Exception Handling Mechanism
with suitable example (8 Marks)
4. Explain the following function
i. rethrow ( ) (4 Marks)
ii. terminate ( ) (4 Marks)
iii. unexpected ( ) and uncaught_exception () (8 Marks)
5. (a)What are the disadvantages of the Exception handling mechanism?
(8 Marks)
6.
(b)What are specifications in throw? In which case are they needed?
(8 Marks)
7. When do we need multiple catch blocks for a single try block? Give an
example (16 Marks)

1) Give the evolution diagram of OOPS concept.


Machine language
Procedure language
Assembly language
OOPS Pg: 4
2) Draw the structure of Procedure oriented language or typical organization of
Procedure oriented language.Pg.7
3) What is Procedure oriented language?
Conventional programming, using high-level language such as COBOL, FORTRAN and
C are commonly known as Procedure oriented language (POP). In POP number of
functions is written to accomplish the tasks such as reading, calculating and printing.
4) Give some characteristics of procedure-oriented language.
• Emphasis is on doing things (algorithms).
• Larger programs are divided into smaller programs known as functions.
• Most of the functions share global data.
• Data move openly around the system from function to function.
• Employs top-down approach in program design.
Function-1 Function-2 Function-3
Function-4 Function-5
Function-6 Function-7 Function-8
Main program
dia Pg:5
5) Write any four features of OOPS.
• Emphasis is on data rather than on procedure.
• Programs are divided into objects.
• Data is hidden and cannot be accessed by external functions.
• Follows bottom -up approach in program design.
6) What are the basic concepts of OOPS?
• Objects.
• Classes.
• Data abstraction and Encapsulation.
• Inheritance.
• Polymorphism.
• Dynamic binding.
• Message passing.
7) What are objects?
Objects are basic run-time entities in an object-oriented system. They may represent a
person, a place, a bank account, a table of data or any item that the program has to
handle. Each object has the data and code to manipulate the data and theses objects
interact with each other.
8)What is a class?
• The entire set of data and code of an object can be made a user-defined data type with
the help of a class.
• Once a class has been defined, we can create any number of objects belonging to the
classes.
• Classes are user-defined data types and behave like built-in types of the programming
language.
9) What is encapsulation?
Wrapping up of data and function within the structure is called as encapsulation.
10) What is data abstraction?
The insulation of data from direct access by the program is called as data hiding or
information binding.
The data is not accessible to the outside world and only those functions, which are
wrapped in the class, can access it.
11) What are data members and member functions?
Classes use the concept of abstraction and are defined as a list of abstract attributes such
as size, weight, and cost and uses functions to operate on these attributes.
The attributes are sometimes called as data members because they hold information. The
functions that operate on these data are called as methods or member functions.
Eg: int a,b; // a,b are data members
Void getdata ( )
{cin>>a;}
// member function
12) what is dynamic binding or late binding?
Binding refers to the linking of a procedure to the code to be executed in response to the
call. Dynamic binding means that the code associated with a given procedure call is not
known until the time of the call at the run-time.
13) Write the process of programming in an object-oriented language?
• Create classes that define objects and their behavior.
• Creating objects from class definition.
• Establishing communication among objects.
14) Give any four advantages of OOPS.
• The principle of data hiding helps the programmer to build secure programs that cannot
be invaded by code in other parts of the program.
• It is possible to have multiple instances of an object to co-exist without any
interference.
• Object oriented programming can be easily upgraded from small to large systems.
• Software complexity can be easily managed.
15) What are the features required for object-based programming Language?
• Data encapsulation.
• Data hiding and access mechanisms.
• Automatic initialization and clear up of objects.
• Operator overloading.
16) What are the features required for object oriented language?
• Data encapsulation.
• Data hiding and access mechanisms.
• Automatic initialization and clear up of objects.
• Operator overloading.
• Inheritance.
• Dynamic binding.
17)Give any four applications of OOPS
• • Real-time systems.
• • Simulation and modeling.
• • Object-oriented databases.
• • AI and expert systems.
18) Give any four applications of c++?
• Since c++ allows us to create hierarchy-related objects, we can build special objectoriented
libraries, which can be used later by many programmers.
• C++ are easily maintainable and expandable.
• C part of C++ gives the language the ability to get close to the machine-level details.
• It is expected that C++ will replace C as a general-purpose language in the near future.
19) What are tokens?
The smallest individual units in a program are known as tokens. C++ has the following
tokens,
• Keyword
• Identifiers
• Constants
• Strings
• Operator
20)What are keywords?
The keywords implement specific C++ language features. They are explicitly reserved
identifiers and cannot be used as names fro the program variables or other user defined
program elements.
Eg: go to, If, struct , else ,union etc.
21) Rules for naming the identifiers in C++.
• Only alphabetic characters, digits and underscore are permitted.
• The name cannot start with a digit.
• The upper case and lower case letters are distinct.
• A declared keyword cannot be used as a variable name.
22)What are the operators available in C++?
All operators in C are also used in C++. In addition to insertion operator << and
extraction operator >> the other new operators in C++ are,
: Scope resolution operator
: : * Pointer-to-member declarator
->* Pointer-to-member operator
.* Pointer-to-member operator
delete Memory release operator
endl Line feed operator
new Memory allocation operator
setw Field width operator
23)What is a scope resolution operator?
Scope resolution operator is used to uncover the hidden variables. It also allows access to
global version of variables.
Eg:
#include<iostream. h>
int m=10; // global variable m
void main ( )
{
int m=20; // local variable m
cout<<”m=”<<m<<”\n”;
cout<<”: : m=”<<: : m<<”\n”;
}
output:
20
10 (: : m access global m)
Scope resolution operator is used to define the function outside the class.
Syntax:
Return type <class name> : : <function name>
Eg:
Void x : : getdata()
24) What are free store operators (or) Memory management operators?
New and Delete operators are called as free store operators since they allocate the
memory dynamically.
New operator can be used to create objects of any data type.
Pointer-variable = new data type;
Initialization of the memory using new operator can be done. This can be done as,
Pointer-variable = new data-type(value)
Delete operator is used to release the memory space for reuse. The general form of its use
is
Delete pointer-variable;
25) What are manipulators?
Setw, endl are known as manipulators.
Manipulators are operators that are used to format the display. The endl manipulator
when used in an output statement causes a linefeed to be inserted and its effect is similar
to that of the newline character”\n”.
Eg:Cout<<setw(5)<<sum<<endl;
26) What do you mean by enumerated datatype?
An enumerated datatype is another user-defined datatype, which provides a way for
attaching names to numbers, thereby increasing comprehensibility of the code.The syntax
of an enum statement is similar to that of the struct statesmen.
Eg:
enum shape{ circle, square, triangle}
enum color{ red, blue, green, yellow}
27) What are symbolic constants?
There are two ways for creating symbolic constants in C++:
• Using the qualifier constant.
• Defining a set of integer constants using enum keyword.
The program in any way cannot modify the value declared as constant in c++.
Eg:
Const int size =10;
Char name [size];
28)What do you mean by dynamic initialization of variables?
C++ permits initialization of the variables at run-time. This is referred to as dynamic
initialization of variables.
In C++ ,a variable can be initialized at run-time using expressions at the place of
declaration as,
……..
…......
int n =strlen(string);
……..
float area=3.14*rad*rad;
Thus declaration and initialization is done simultaneously at the place where the variable
is used for the first time.
29) What are reference variable?
A reference variable provides an alias(alternative name) for a previously defined
variable.
sum total For example , if make the variable a reference to the variable , then sum and
total can be used interchancheably to represent that variable.
Syntax :
Data-type &reference-name = variable-name
Eg:
float total = 100;
float sum = total;
30)What is member-dereferencing operator?
C++ permits to access the class members through pointers. It provides three pointer-tomember
operators for this purpose,
: :* To declare a pointer to a member of a class.
* To access a member using object name and a pointer to the member
->* To access a member using a pointer to the object and a pointer to that member.
31)what is function prototype ?
The function prototype describes function interface to the compiler by giving details such
as number ,type of arguments and type of return values
Function prototype is a declaration statement in the calling program and is of the
following
Type function_name(argument list); Eg float volume(int x,float y);
32)what is an inline function ?
An inline function is a function that is expanded in line when it is invoked. That is
compiler replaces the function call with the corresponding function code.
The inline functions are defined as Inline function-header
{
function body
}
33) Write some situations where inline expansion may not work
• for functions returning values, if loop, a switch, or a goto exists
• for functions not returning values ,if a return statement exists
• if function contain static variables
• if inline functions are recursive
34)what is a default argument ?
Default arguments assign a default value to the parameter, which does not have matching
argument in the function call. Default values are specified when the f unction is declared.
Eg : float amount(float principle,int period,float rate=0. 15)
Function call is
Value=amount(5000,7);
Here it takes principle=5000& period=7
And default value for rate=0.15
Value=amount(5000,7,0.34)
Passes an explicit value 0f 0.34 to rate
We must add default value from right to left
35) What are constant arguments ?
Keyword is const. The qualifier const tells the compiler that the function should not
modify the argument. The compiler will generate an error when this condition is violated.
This type of declaration is significant only when we pass arguments by reference or
pointers
eg: int strlen( const char *p);
36) How the class is specified?
Generally class specification has two parts
• class declaration
It describes the type and scope of its member
• class function definition
It describes how the class functions are implemented
The general form is
Class class_name
{
private:
variable declarations;
function declaration;
public:
variable declaration;
function declaration;
};
37) How to create an object ?
Once the class has been declared, we can create variables of that type by using the
classname
Eg: classname x; //memory for x is created
38) How to access a class member?
object-name. function-name (actual arguments)
eg:x.getdata(100,75.5);
39) How the member functions are defined ?
Member functions can be defined in two ways
• outside the class definition
Member function can be defined by using scope resolution operator::
General format is
Return type class_ name::function-name(argument declaration)
{
}
• Inside the class definition
This method of defining member function is to replace the function declaration by the
actual function definition inside the class. It is treated as inline function
Eg:class item
{
int a,b ;
void getdata(int x,int y)
{
a=x;
b=y;
};
40) What is static data member?
Static variable are normally used to maintain values common to the entire class.
Feature:
• It is initialized to zero when the first object is created. No other initialization is
permitted
• only one copy of that member is created for the entire class and is shared by all the
objects
• It is only visible within the class, but its life time is the entire class type and scope of
each static member variable must be defined outside the class
• It is stored separately rather than objects
Eg: static int count//count is initialized to zero when an object is created.
int classname::count;//definition of static data member
41) What is static member function?
A member function that is declared as static has the following properties
• A static function can have access to only other static member declared in the same class
• A static member function can be called using the classname as follows
classname ::function_name;
42) How the objects are used as function argument?
This can be done in two ways
• A copy of the entire object is passed to the argument
• only address of the objects is transferred to the f unction
43) what is called pass by reference?
In this method address of an object is passed, the called function works directly on the
actual arguments.
44) Define const member
If a member function does not alter any data in the class, then we may declare it as const
member function as
Void mul(int ,int)const;
45) Define pointers to member
It is possible to take the address of a member of a class and assign it to a pointer. The
address of a member can be obtained by applying the operator &to a “fully qualified”
class member name. A class member pointer can be declared using the operator::*with
the class name.
Eg: class A
{
int m;
public:
void show( );
};
pointer to member m is defined as
int A::*ip=&A::m;
A::*->pointer to member of A class
&A::m->address of the m member of A class
46) When the deferencing operator ->* is used?
It is used to access a member when we use pointer to both the object and the member.
47) When the deferencing operator .* is used?
It is used to access a member when the object itself is used as pointers.
48) Define local classes.
Classes can be defined and used inside a function or a block. such classes are called local
classes. It can use global variables and static variables declared inside the function but
cannot use automatic local variables.
Eg;
void test(int a)
{
…….
}
class student
{
………
};
student s1(a);
}
49) Define constructor
A constructor is a special member function whose task is to initialize the objects of its
class. It is special because its name is same as class name. The constructor is invoked
whenever an object of its associated class is created. It is called constructor because it
constructs the values of data members of the class
Eg:
integer Class
{
……
public:
integer( );//constructo r
………
}
50) Define default constructor
The constructor with no arguments is called default constructor
Eg:
Class integer
{
int m,n;
Public:
Integer( );
…….
};
integer::integer( )//default constructor
{
m=0;n=0;
}
the statement
integer a;
invokes the default constructor
51) Define parameterized constructor
constructor with arguments is called parameterized constructor
Eg;
Class integer
{ int m,n;
public:
integer(int x,int y)
{ m=x;n=y;
}
To invoke parameterized constructor we must pass the initial values as arguments to the
constructor function when an object is declared. This is done in two ways
1.By calling the constructor explicitly
eg: integer int1=integer(10,10);
2.By calling the constructor implicitly
eg: Integer int1(10,10);
52) Define default argument constructor
The constructor with default arguments are called default argument constructor
Eg:
Complex(float real,float imag=0);
The default value of the argument imag is 0
The statement complex a(6.0)
assign real=6.0 and imag=0
the statement
complex a(2.3,9.0)
assign real=2.3 and imag=9.0
53) What is the ambiguity between default constructor and default argument
constructor ?
The default argument constructor can be called with either one argument or no
arguments. When called with no arguments, it becomes a default constructor. When both
these forms are used in a class, it cause ambiguity for a statement such as A a;
the ambiguity is whether to call A::A () or A::A (int i=0)
54) Define copy constructor
A copy constructor is used to declare and initialize an object from another object. It takes
a reference to an object of the same class as an argument
Eg: integer i2 (i1);
would define the object i2 at the same time initialize it to the values of i1.
Another form of this statement is
Eg: integer i2=i1;
The process of initializing through a copy constructor is known as copy initialization .
55) Define dynamic constructor
Allocation of memory to objects at time of their construction is known as dynamic
constructor. The memory is allocated with the help of the NEW operator
Eg:
Class string
{
char *name;
int length;
public:
string( )
{
length=0;
name=new char[ length +1];
}
void main( )
{
string name1(“Louis”),name3(Lagrange);
}
56) Define const object
We can create constant object by using const keyword before object declaration.
Eg: Const matrix x(m,n);
57) Define destructor
It is used to destroy the objects that have been created by constructor. Destructor name is
same as class name preceded by tilde symbol (~)
Eg;
~integer ()
{
}
A destructor never takes any arguments nor it does it return any value. The compiler upon
exit from the program will invoke it. new Whenever operator is used to allocate memory
in the constructor, we should
use delete to free that memory.
58) Define multiple constructors (constructor overloading).
The class that has different types of constructor is called multiple constructors
Eg:
#include<iostream. h>
#include<conio.h>
class integer
{
int m,n;
public:
integer( ) //default constructor
{
m=0;n=0;
}
integer(int a,int b) //parameterized constructor
{
m=a; n=b;
}
integer(&i) //copy constructor
{
m=i. m;
n=i.n;
}
void main()
{
integer i1; //invokes default constructor
integer i2(45,67);//invokes parameterized constructor
integer i3(i2); //invokes copy constructor
}
59) Write some special characteristics of constructor
• T hey should be declared in the public section
• They are invoked automatically when the objects are created
• They do not have return types, not even void and therefore, and they cannot return
values
• They cannot be inherited, though a derived class can call the base class
• They can have default arguments
• Constructors cannot be virtual f unction
60) How the objects are initialized dynamically?
To call parameterized constructor we should the pass values to the object ie,for the
constructor integer(int a,int b) it is invoked by integer a(10,18)
this value can be get during run time. i.e., f or above constructor
int p,q;
cin>>p>>q;
integer a(p,q);
61)Define Inline Function?
Inline function is defined as a function definition such that each call to the function is in
effect, replaced by the statements that define the function. It is expanded in line when it is
invoked. The general form is
inline function-header
{
function body
}
62)Explain return by reference with an example.
A function can also return a reference. Consider the following function
int & max( int &x , int &y)
{ if(x>y)
return x;
else
return y;
}
Since the return type of max ( ) is int & the function returns reference to x or y (and not
the values). Then a function call such as max ( a , b) will yield a reference to either a or b
depending on their values.
The statement
max ( a , b) = -1;
is legal and assigns –1 to a if it is larger, otherwise –1 to b.
63) What are Friend functions? Write the syntax
A function that has access to the private member of the class but is not itself a member of
the class is called friend functions.
The general form is
friend data_type function_name( );
Friend function is preceded by the keyword ‘friend’.
64) Write some properties of friend functions.
• Friend function is not in the scope of the class to which it has been declared as friend.
Hence it cannot be called using the object of that class.
• Usually it has object as arguments.
• It can be declared either in the public or private part of a class.
• It cannot access member names directly. It has to use an object name and dot
membership operator with each member name. eg: ( A . x )
65)What are virtual functions?
A function qualified by the ‘virtual’ keyword is called virtual function. When a virtual
function is called through a pointer, class of the object pointed to determine which
function definition will be used.
66)Write some of the basic rules for virtual functions
• Virtual f unctions must be member of some class.
• They cannot be static members and they are accessed by using object pointers
• Virtual f unction in a base class must be defined.
• Prototypes of base class version of a virtual function and all the derived class versions
must be identical.
• If a virtual function is defined in the base class, it need not be redefined in the derived
class.
67) What are pure virtual functions? Write the syntax.
A pure virtual function is a function declared in a base class that has no definition relative
to the base class. In such cases, the compiler requires each derived class to either define
the function or redeclare it as a pure virtual function. A class containing pure virtual
functions cannot be used to declare any object of its own. It is also known as “donothing”
function.
The “do-nothing” function is defined as follows:
virtual void display ( ) =0;
68) What is polymorphism? What are its types?
Polymorphism is the ability to take more than one form. An operation may exhibit
different behaviors in different. The behavior depends upon the type of data used.
Polymorphism is of two types. They are
• Function overloading
• Operator overloading
69) What is function overloading? Give an example.
Function overloading means we can use the same function name to create functions that
perform a variety of different tasks.
Eg: An overloaded add ( ) function handles different data types as shown below.
// Declarations
i. int add( int a, int b); //add function with 2 arguments of same type
ii. int add( int a, int b, int c); //add function with 3 arguments of same type
iii. double add( int p, double q); //add function with 2 arguments of
different type
//Function calls
add (3 , 4); //uses prototype ( i. )
add (3, 4, 5); //uses prototype ( ii. )
add (3 , 10.0); //uses prototype ( iii. )
70) What is operator overloading?
C++ has the ability to provide the operators with a special meaning for a data type. This
mechanism of giving such special meanings to an operator is known as Operator
overloading. It provides a flexible option for the creation of new definitions for C++
operators.
71) List out the operators that cannot be overloaded.
• Class member access operator (. , .*)
• Scope resolution operator (::)
• Size operator ( sizeof )
• Conditional operator (?:)
72) What is the purpose of using operator function? Write its syntax.
To define an additional task to an operator, we must specify what it means in relation to
the class to which the operator is applied. This is done by Operator function , which
describes the task. Operator functions are either member functions or friend functions.
The general form is
return type classname :: operator (op-arglist )
{
function body
}
where return type is the type of value returned by specified operation.
op- operator being overloaded. The op is preceded by a keyword operator. operator op is
the function name.
73) Write at least four rules for Operator overloading.
• Only the existing operators can be overloaded.
• The overloaded operator must have at least one operand that is of user defined data
type.
• The basic meaning of the operator should not be changed.
• Overloaded operators follow the syntax rules of the original operators. They cannot be
overridden.
74) How will you overload Unary & Binary operator using member functions?
When unary operators are overloaded using member functions it takes no explicit
arguments and return no explicit values. When binary operators are overloaded using
member functions, it takes one explicit argument. Also the left hand side operand must be
an object of the relevant class.
75) How will you overload Unary and Binary operator using Friend functions?
When unary operators are overloaded using friend function, it takes one reference
argument (object of the relevant class) When binary operators are overloaded using friend
function, it takes two explicit
arguments.
76) How an overloaded operator can be invoked using member functions?
In case of Unary operators, overloaded operator can be invoked as op object_name or
object_name op
In case of binary operators, it would be invoked as Object . Operator op(y)
where op is the overloaded operator and y is the argument.
77) How an overloaded operator can be invoked using Friend functions?
In case of unary operators, overloaded operator can be invoked as Operator op (x);
In case of binary operators, overloaded operator can be invoked as Operator op (x , y)
78) List out the operators that cannot be overloaded using Friend function.
• Assignment operator =
• Function call operator ( )
• Subscripting operator [ ]
• Class member access operator
79) What is meant by casting operator and write the general form of overloaded
casting operator.
A casting operator is a function that satisfies the following conditions
• It must be a class member.
• It must not specify a return type.
• It must not have any arguments.
The general form of overloaded casting operator is
operator type name ( )
{
……….. // function statements
}
It is also known as conversion function.
80) Explain basic to class type conversion with an example.
Conversion from basic data type to class type can be done in destination class.
Using constructors does it. Constructor takes a single argument whose type is to be
converted.
Eg: Converting int type to class type
class time
{
int hrs,mins;
public:
………….
Time ( int t) //constructor
{
hours= t/60 ; //t in minutes
mins =t % 60;
}
};
Constructor will be called automatically while creating objects so that this conversion is
done automatically.
81) Explain class to basic type conversion with an example.
Using Type Casting operator, conversion from class to basic type conversion can be
done. It is done in the source class itself.
Eg: vector : : operator double( )
{
double sum=0;
for(int I=0;I<size;I++)
sum=sum+v[ i ] *u[ i ] ;
return sqrt ( sum ) ;
}
This function converts a vector to the corresponding scalar magnitude.
82) Explain one class to another class conversion with an example.
Conversion from one class type to another is the combination of class to basic and basic
to class type conversion. Here constructor is used in destination class and casting operator
function is used in source class.
Eg: objX = objY
objX is the object of class X and objY is an object of class Y. The class Y type data is
converted into class X type data and the converted value is assigned to the obj X. Here
class Y is the source class and class X is the destination class.