C++ Oops
C++ Oops
C++ Oops
Zerone - Stands for Zero (0) and One (1), the very basics of computing. So Binary Matters.
Infact only Binary Matters in our world of computers. The motive behind Zerone is to make job
hunting an easier process or atleast that is what we intent to. This is a one stop jobs group.
N
The content in this document is collected from various groups, sites & media. Copyright belongs
to respective owners. If you have any copyright issues, please mail to legal@zeroneworld.com
with complete details.
O
"If You Have An Apple And I Have An Apple And We Exchange Apples Then You And I
Will Still Each Have One Apple. But If You Have An Idea And I Have An Idea And We
Exchange These Ideas, Then Each Of Us Will Have Two Ideas."
--- George Bernard Shaw (1856-1950)
R
1) class Sample
{
public:
E
int *ptr;
Sample(int i)
{
ptr = new int(i);
}
~Sample()
N
O
{
delete ptr;
}
void PrintVal()
R
{
cout << "The value is " << *ptr;
}
ZE
};
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:
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;}
};
E
class deri:public base
{
public:
int dval;
deri(){ dval=1;}
N
O
};
void SomeFunc(base *arr,int size)
{
for(int i=0; i<size; i++,arr++)
R
cout<<arr->bval;
cout<<endl;
}
ZE
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
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)
{
E
baseObj->baseFun();
}
int main()
{
base baseObject;
SomeFunc(&baseObject);
N
O
deri deriObject;
SomeFunc(&deriObject);
}
Answer:
R
from base
from base
Explanation:
ZE
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()
void main()
{
int a, *pa, &ra;
E
pa = &a;
ra = a;
cout <<"a="<<a <<"*pa="<<*pa <<"ra"<<ra ;
}
/*
Answer :
N
O
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,
R
void main()
{
int a[size] = {1,2,3,4,5};
int *b = new int(size);
print(a);
print(b);
}
/*
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;
}
};
E
void main()
{
}
some s;
s.~some();
N
O
/*
Answer:
some's destructor
some's destructor
R
Explanation:
Destructors can be called explicitly. Here 's.~some()' explicitly calls the
destructor of 's'. When main() returns, destructor of s is called again,
ZE
#include <iostream.h>
class fig2d
{
int dim1;
int dim2;
public:
fig2d() { dim1=5; dim2=6;}
void main()
{
E
fig2d obj1;
// fig3d obj2;
//
}
obj1 << cout;
obj2 << cout;
N
O
/*
Answer :
56
Explanation:
R
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.
E
class complex{
double re;
double im;
public:
complex() : re(1),im(0.5) {}
bool operator==(complex &rhs);
N
O
operator int(){}
};
return false;
}
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{
void main(){
complex c3;
double i=5;
c3 = i;
c3.print();
}
Answer:
5,5
E
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. N
O
void main()
{
int a, *pa, &ra;
pa = &a;
R
ra = a;
cout <<"a="<<a <<"*pa="<<*pa <<"ra"<<ra ;
}
ZE
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
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?
E
4) What is wrong with this class declaration?
class something
{
char *str;
public:
N
O
something(){
st = new char[10]; }
~something()
{
R
delete str;
}
};
ZE
7) Which is the only operator in C++ which can be overloaded but NOT inherited.
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
E
provides the needed information. It’s jargon for plain templates.
Class template:
A class template specifies how individual classes can be constructed much like
plain classes.
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.
ZE
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.
E
s(x);
...
x:=cont_iter.next();
end; N
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
O
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.
R
E
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.
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.
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?
E
Answer:
Ø The condition should hold at the end of every constructor.
Ø The condition should hold at the end of every mutator(non-const) operation.
{
public:
class Array1D
ZE
{
public:
T& operator[] (int index);
const T& operator[] (int index) const;
...
};
Array1D operator[] (int index);
const Array1D operator[] (int index) const;
...
};
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
E
23. What is a node class?
Answer:
A node class is a class that,
N
Ø 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
O
Ø 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.
R
A node class is a class that has added new services or functionality beyond the
services inherited from its base class.
ZE
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.
E
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.
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.
E
public:
int do_it(int)
{
};
}
return fwrite( ).suceed( ); N
O
class error_message: public Action
{
response_box db(message.cstr( ),"Continue","Cancel","Retry");
switch (db.getresponse( ))
R
{
case 0: return 0;
case 1: abort();
ZE
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.
E
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
N
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
O
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.
R
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.
X& operator *( );
const X& operator*( ) const;
X* operator->() const;
E
cout<<*p;
p->raise_salary(0.5);
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
E
ival becomes something like:
// a possible member name mangling
ival__3Bar
Consider this derivation:
{
class Foo : public Bar
public:
N
O
int ival;
...
}
R
The internal representation of a Foo object is the concatenation of its base and
derived class members.
// Pseudo C++ code
ZE
E
41. What is cloning?
Answer:
N
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.
O
42. Describe the main characteristics of static functions.
Answer:
The main characteristics of static functions include,
Ø It is without the a this pointer,
R
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.
E
{
return new(buffer) Widget(widgetsize);
}
}; N
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
O
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.
R
OOAD
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.
E
are considered as non-persistent.
Diagram:
client server
(Active) (Passive)
ZE
Ø 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.
E
ex:
car contains wheels, etc.
car
car N
wheels
Ø Containment: This relationship is applied when the part contained with in the
O
whole part, dies when the whole part dies.
It is represented as darked diamond at the whole part.
example:
class A{ //some code };
R
};
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 A class B
class A
class B class C
E
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
N
that got affected. The human body is an apt example for this relationship. When the
whole body dies the parts (heart etc) are died.
O
13. 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.
R
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.
E
It is represented as a stickman like this.
Diagram:
N
O
20. What is guard condition?
Guard condition is one, which acts as a firewall. The access from a particular
object can be made only when the particular condition is met.
R
For Example,
customer check customer number ATM.
Here the object on the customer accesses the ATM facility only when the guard
ZE
condition is met.
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,
calculate pay calculate
class1 class2 class3
class A
<< Actor>>
attributes
methods.
E
ex:
class person
{
public:
char getsex();
void setsex(char);
N
O
void setsex(int);
};
In the above example we see that there is a function setsex() with same name
but with different signature.
R
ZE