C++ Questions: Calypso
C++ Questions: Calypso
C++ Questions: Calypso
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
1
calypso
up with ptr that has been freed.The solution is to pass the Sample object by
reference to SomeFunc:
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;}
};
int main()
{
base BaseArr[5];
SomeFunc(BaseArr,5);
deri DeriArr[5];
SomeFunc(DeriArr,5);
}
Answer:
2
calypso
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
{
3
calypso
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.
*/
4
calypso
{
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:
5
calypso
#include <iostream.h>
class fig2d
{
int dim1;
int dim2;
public:
fig2d() { dim1=5; dim2=6;}
void main()
{
fig2d obj1;
// fig3d obj2;
6
calypso
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);
};
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;
7
calypso
public:
complex() : re(1),im(0.5) {}
bool operator==(complex &rhs);
operator int(){}
};
int main(){
complex c1;
cout<< c1;
}
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:
8
calypso
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
9
calypso
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?
7) Which is the only operator in C++ which can be overloaded but NOT inherited.
10
calypso
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
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.
11
calypso
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.
12
calypso
13
calypso
class. In particular all class invariants are both preconditions and post-conditions for
all operations or member functions of the class.
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.
Answer:
Objects that stand for other objects are called proxy objects or surrogates.
Example:
template<class T>
class Array2D
{
public:
class Array1D
{
public:
14
calypso
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.
Answer:
Smalltalk,
Java,
Eiffel,
Sather.
Answer:
sizeof . .* .-> :: ?:
15
calypso
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.
16
calypso
function.
class Action
{
public:
virtual int do_it( int )=0;
virtual ~Action( );
}
17
calypso
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:
A user of the Action class will be completely isolated from any knowledge of
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.
18
calypso
19
calypso
{
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;
20
calypso
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.
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
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
21
calypso
int ival__3Foo;
...
};
Unambiguous access of either ival members is achieved through name mangling.
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).
exactly one definition of every object, function or class used in a C++ program.
22
calypso
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.
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.
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
23
calypso
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
OOAD
24
calypso
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.
Diagram:
client server
(Active) (Passive)
25
calypso
Aggregation: Its' the relationship between two classes which are related in the
fashion that master and slave. The master takes full rights than the slave. Since
the slave works under the master. It is represented as line with diamond in the
master area.
ex:
car contains wheels, etc.
car
car wheels
Containment: This relationship is applied when the part contained with in the
whole part, dies when the whole part dies.
It is represented as darked diamond at the whole part.
example:
class A{
//some code
};
class B
{
A aa; // an object of class A;
// some code for class B;
};
In the above example we see that an object of class A is instantiated with in
the class B. so the object class A dies when the object class B dies.we can represnt it
in diagram like this.
class B
class A
26
calypso
class A
class B class C
27
calypso
15. 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.
16. 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.
Booch: In this method classes are represented as "Clouds" which are not very
easy to draw as for as the developer's view is concern.
Diagram:
28
calypso
In the above representation I, obj1 sends message to obj2. But in the case of II
the data is transferred from obj1 to obj2.
22. USECASE is an implementation independent notation. How will the designer give
the implementation details of a particular USECASE to the programmer?
This can be accomplished by specifying the relationship called "refinement”
which talks about the two different abstraction of the same thing.
Or example,
23. Suppose a class acts an Actor in the problem domain, how to represent it in the
static model?
In this scenario you can use “stereotype”. Since stereotype is just a string that
gives extra semantic to the particular entity/model element. It is given with in the <<
>>.
class A
29
calypso
<< Actor>>
attributes
methods.
30
calypso
31