C++ Material : Placement Preparation


hi friends these are some faq's on C++ programming as per collected from various years and companies papers . hope this will you in your preparations..


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 DOS/Windows environment,
Ø Proper and required header files are inlcuded,
Ø The underlying machine is an x86 based system,
The program output may depend on the information based on this assumptions.
1. What is the output of the following program?
void main(){
char str[] = "String continued"
" at the next line";
cout << str;
}
Answer:
String continued at the next line.
Explanation:
C++ concatenates these strings. When a new-line or white spaces separate two adjacent strings, they are concatenated to a single string. This operation is called as ―stringization‖ operation. So str could have initialized by the single string ―String continued at the next line.‖.
2. void main(){
int a, *pa, &ra;
pa = &a;
ra = a;
cout <<"a="<<<"*pa="<<*pa <<"ra"< (pBase);
4. const int size = 5;
void print(int *ptr){
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.
7. What is the output of the following program?
void Sample(int x=6,int y,int z=34){
cout << "Say i am in sample with the values " <<<>a>>b>>c;
Sample(a,b,c);
}
Answer:
Compile Time error: Missing default parameter for parameter 2.
Explanation:
The program wouldn‘t compile because, as far as default arguments are concerned, the right-most argument must be supplied with a default value before a default argument to a parameter to it‘s left can be supplied.
8. 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<bval;
cout<= sizeof(int)+sizeof(int) ).
9. class some{
public:
~some(){
cout<<"some's destructor"<<<"from base"<<< "from derived"<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.
11. class base{
public:
virtual void baseFun(){ cout<<"from base"<<< "from derived"<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.
12. What is the output of the following code?
class base
{
public:
int n;
virtual void foo(){n=1;}
void print(){cout <<<<(&y);
bp->foo();
bp->print();
}
Answer:
Undefined behavior : dynamic_cast used to convert to inaccessible or ambiguous base;
Explanation:
In this program private inheritance is used (by default the inheritance is private). There is no implicit conversion from the derived to base due to this. An explicit dynamic cast is used to overcome this. But at runtime environment may impose the restrictions on access to the code, resulting in an undefined behavior.
13. class fig2d{
int dim1, dim2;
public:
fig2d() { dim1=5; dim2=6;}
virtual void operator<<(ostream & rhs);
};
void fig2d::operator<<(ostream &rhs){
rhs <dim1<<" "<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<dim3;
}
void main(){
fig2d obj1;
fig3d obj2;
obj1 << cout;
obj2 << cout;
}
Answer :
5 6
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, operator << is implemented as global function, but it doesn't mean that it 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.
14. class opOverload{
public:
bool operator==(opOverload temp);
};
bool opOverload::operator==(opOverload temp){
if(*this == temp ){
cout<<"The both are same objects\n";
return true;
}
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.
15. class complex{
double re;
double im;
public:
complex() : re(1),im(0.5) {}
operator int(){}
};
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 class.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.
16. 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<<<<"Received exception, but can't handle\n";
throw;
}
};
void main()
{
try
{
foo();
}
catch (derived d)
{
cout<<"In derived handler";
}
catch (base b)
{
cout << "In Base handler";
}
}
Answer:
Received exception, but can't handle
In derived handler
Explanation:
When the function foo is called, the exception object of type derived is thrown. Now the catch block for that ‗derived‘ exception object is searched but it is found that there is a catch block for ‗base‘ is available. Since exception objects of type ‗base‘ can handle all such exceptions in its hierarchy, this exception is caught.
A plain ‗throw‘ inside a catch indicates a re-throw of the exception caught. So the ‗derived‘ exception object is again thrown and is caught by the catch block in main(). Although both the catch blocks are eligible to handle the exception, this time the derived which is defined first will catch the exception.
19. What is the output of the following program?
void main(){
vector vec1,vec2;
vec1.push_back(12);
vec1.push_back(13);
vec2.push_back(12);
vec2.push_back(13);
cout << (vec1 aList;
list::iterator anIterator(&aList);
what can you say about the relationship between ‗aList‘ and ‗anIterator‘?
Answer:
The class iterator is a friend of class list.
Explanation:
Iterators are always friend functions.
21. #include
#include
#include
using namespace std;
void main()
{
list ilist;
list::iterator iiter;
for (int i=0;i<10;i++) ilist.push_back(i);
iiter = find(ilist.begin(),ilist.end(),3);
if ( *(iiter+1) ==4) cout <<"yeah ! found";
}
Output:
Compile –time error:
Explanation:
The code won‘t compile because , iterators associated with list containers do not support the operator + used in the expression (*(iter+1) ==4 ), because iterators associated with list are of type bi-directional iterator, which doesn‘t support the + operator.
Exercise:
1) Determine the output of the following 'C++' Codelet.
class base{
public :
out() {
cout<<"base ";
}
};
class deri : public base{
public : out(){
cout<<"deri ";
}
};
void main(){
deri dp[3];
base *bp = (base*)dp;
for (int i=0; i<3;i++)
(bp++)->out();
}
2) Is there anything wrong with this C++ class declaration?
class something{
char *str;
public:
something(){
st = new char[10];
}
~something(){
delete str;
}
};
3) 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;
}
};
22. Name the four parts of a declaration.
Ø A set of specifiers
Ø A base type
Ø A declarator
Ø An optional initializer
23. 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.
24. Differentiate between initialization and assignment
Initialization is the process that creates the first value of an object. Assignment on the other hand is an operation that usually changes the value of an object. Assignment is expressed using the token '=' but sometimes initialization can also be indicated with that symbol.
int a=12; // Initialization
a=13; // Assignment
Initialization can also occur without the '=' token, as well. For example,
int a(12);
For classes, you can define your own initialization procedure by providing constructors and your own assignment operation by providing constructors and your own assignment operation by providing an operator '=' will not be called for initialization is expressed using the '=' symbol.
25. Find five different C++ constructs for which the meaning is undefined an for which the meaning is implementation defined.
Undefined behavior in C++
1. Access outside the bounds of an array.
int a[10];
int *p=&a[10];
2. Use of a destroyed object
int &r=*new int;
delete &r;
r=r+1;
3. Attempting to reinterpret variables
int i;
*(float*)&i=1.0;
//Access through undeclared type
4. Casting to a type that is not the real type of the source object
struct B {int i;}
struct D:B{}
B *bp=new B;
D* dp=static_cast (bp); //Invalid cast
5. Casting away constness of an object that was defined const
void f(int const &r)
{
const_cast (r)=2;
}
int const i=3;
f(i); // Invalid
Five implementation-defined constructs in C++
1. Size of certain types:
sizeof(int);
2. Output of type_info :: name()
std::cout< =max()
5. The number of temporary copies
struct s
{
s(s const&)
{
std::cout<<"copy\n ";
}
}
s f( )
{
s a;
return a;
}
int main()
{
f();return 0;
}
26. When is a volatile qualifier is required to be used?
In certain cases, you don't want the compiler to produce optimizations. When dealing with variables that are accessible both from an interrupt servicing routine (ISR) and by the regular code, the compiler should not make any assumptions about the value of a variable from one line of code to the next. Similarly, in a multiprocessing environment, there may be other processors that have access to shared memory variables, thereby making changes to them without warning. In such cases that involve memory mapped hardware devices, you need the volatile qualifier. Volatile qualifier prevents any optimizations done on the names they qualify, making the program possible to be used in such environments.
27. What is the use of qualifier 'mutable'?
The mutable qualifier is used to indicate that a particular member of a structure or class can be altered even if a particular structure or class variable is a const.
Example:
struct data
{
char name[30];
mutable int noOfAccesses;
..........
};
.........
const data d1{"some string ",0,.......};
strcpy(d1.name,"another string"); // not allowed
d1.noOfAccesses++; // allowed
The const qualifier to d1 prevents a program from changing d1's members, but the mutable qualifier to the accesses member shields accesses from that restriction.
28. In c++ by default, all functions have external storage class, they can be shared across files. What are the functions to which the above statement proves false.
Inline functions and functions qualified with the keyword static have internal linkage and are confined to the defining file.
29. What is the ODR?
The requirement that global objects and functions either have only one definition or have exactly the same definition many times in a program is called the one definition rule(ODR).
30. When do implicit type conversions occur?
Ø In an arithmetic expression of mixed types. These are known as arithmetic conversions.
Ø In the assignment of an expression of one type to an object of another
Ø When passing arguments to functions
Ø Function return types.
31. List the predefined conversions available in C++.
C++ supplies certain conversions for all types, and these apply to all classes as well. These include,
Ø The trivial conversions between a class and a reference to that class.
Ø The trivial conversion between an array of class objects and a pointer to
that class.
Ø The trivial conversion from a class instance to a const class object.
Ø The standard conversion from a pointer to a class object to the type void*.
The compiler uses these conversions implicitly in matching argument and parameter types.
32. 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.
32. Is there any space(memory) associated with namespaces?
No, because namespaces simply deal with names and no space is allocated for a name within a namespace. It is a way by which variables with same name but with different usage are accommodated into a single program.
33. What are using declarations?
It is possible to make a member of a namespace visible within a program. Using Declarations does this. For example:
namespace MySpace{
char * FileName;
char * FileBuffer[300];
}
using MySpace::FileName;
void main(){
cin >>FileName;
}
In this example we have a namespace that consists of two data members. But we have decided to use only one of those data members. We have specified that we want to use only the member FileName.
34. What are using directives?
Whenever we want to make all the members of a namespace visible within a given program, we use a using directive. This gives a direction to the compiler that it has to look into this namespace for name resolution.
using namespace MySpace;
void main(){
cin >>FileName;
}
Here all the data members of the namespace MySpace are visible within the program.
35. When does a name clash occur?
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.
36. 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.
37. ANSI C++ introduces four version of casts, for four different conversions. What are they and give their purpose.
The new casting syntax introduced are const_cast, static_cast, dynamic_cast and reinterpret_cast.
The general syntax for ANSI C++ style casting is :
toTypeVar = xxx_cast < toType > ( fromTypeVar );
This casting syntax helps programmer to identify the casting that are done in program, and its purpose easily than in C, where it can be easily missed.
const_cast is to be used to remove the const or volatileness involved with that object.
char *str = "something";
strlen( const_cast< const char * > str );
// strlen requires const char * as its argument.
It can also be used to remove the volatileness of the object, but that requirement arises very rarely.
static_cast shall be used in all the cases where C casts are normally used.
char *a;
int * b = static_cast < int * > (a);
This converts from char * to int * and this reqires static_cast.
dynamic_cast is used for traversing up and down in inheritance hierarchy.
Base *bp = new Base();
Deri *dp = dynamic_cast < Deri * > (bp);
It should be noted that this is applicable only to 'safe casts', the types that contain the virtual functions.
reinterpret_cast is the cast that can be applied for pointers (particularly function pointers)
int foo();
void (*fp)() = reinterpret_cast< void (*)() > (foo);
fp();
38. 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.
39. What is an activation record?
The entire storage area of a function is known as the activation record. This is allocated from the program‘s run-time stack. This contains all the information related with the function, such as the value of the parameters passed, the value of the various local variables etc.
40. 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.
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.
41. Which is the parameter that is added implicitly to every non-static member function in a class?
‗this‘ pointer
42. Give few important properties of ‗this‘ pointer
A) The ‗this‘ pointer is an implicit pointer used by the system.
B) The ‗this‘ pointer is a constant pointer to an object.
C) The object pointed to by the ‗this‘ pointer can be de-referenced and modified.
43. 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.
44. 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.
45. 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);
46. How will you decide whether to use pass by reference, by pointer and by value?
The selection of the argument passing depends on the situation.
If a function uses passed data without modifying it,
Ø If the data object is small, such as a built-in data type or a small structure then pass it by value.
Ø If the data object is an array, use a pointer because that is the only choice. Make the pointer a pointer to const.
Ø If the data object is a good-sized structure, use a const pointer or a const reference to increase program efficiency. You save the time and space needed to copy a structure or a class design, make the pointer or reference const.
Ø If the data object is a class object, use a const reference. The semantics of class design often require using a reference. The standard way to pass class object arguments is by reference.
A function modifies data in the calling function,
Ø If the data object is a built-in data type, use a pointer. If you spot a code like fixit(&x), where x is an int, its clear that this function intends to modify x.
Ø If the data object is an array, use the only choice, a pointer.
Ø If the data object is a structure, use a reference or a pointer.
Ø If the data object is a class object, use a reference.
47. 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.
48. 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.
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.
49. Define a way other than using the keyword inline to make a function inline.
The function must be defined inside the class.
50. 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).
51. Name the operators that cannot be overloaded.
sizeof . .* .-> :: ?:
52. List out the rules for selecting a particular function under function overloading.
Ø An exact match is better than a trivial adjustment.
Ø A trivial adjustment (e.g. adding const qualification and/or decaying an array to a pointer to its first element) is preferred over an integral promotion.
Ø Integral promotion - such as conversion from char to int - beat other standard conversions.
Ø Standard conversions are better than user defined conversions.
Ø Matching ellipsis arguments is the worst kind of match.
53. What is the dominance rule?
The dominance rule states that if two classes contain the function searched for, and if one class is derived from the another, the derived class dominates.
54. List out the factors for distinguishing overloaded functions
Ø The functions must contain a different number of arguments,
Ø At least one of the arguments must be different.
The return type of a function is not a factor in distinguishing overloaded functions.
55. Define the intersection rule for overloaded operators.
For overloaded functions with more than one parameter, argument matching is more complex. So, the intersection rule was adopted which uses the following procedure:
1. For each argument in the invocation, determine the set of function definitions that contain the best matches for that argument's type.
2. Take the intersection of these sets, and if the result is not a single definition, then the call is ambiguous.
3. The resulting definition must also match at least one argument better than every other definition.
56. List out the argument matching rules for overloaded function selection within the same type.
1. No conversions are necessary. Functions returning no argument conversions are the best candidates.
2. Argument promotions are necessary. One or more arguments are promoted along the path
char -->int--> float-->double-->long-->double
3. Arguments‘ conversions are necessary. One or more arguments are converted according to standard or user defined conversions.
57. List out the functions that are not (and can't be) inherited in C++.
Ø Constructors,
Ø Destructors,
Ø User defined new operators,
Ø User defined assignment operators,
Ø Friend relationships.
58. Declaring a static member function with the const keyword doesn't make sense. Why?
The purpose of the const keyword is to prevent the modification of the values through ‗this‘ and makes the following invisible declaration:
const example *const this;
The static member functions are not passed with an invisible ‗this‘ pointer when they are called. So it doesn‘t make any sense to declare a static member function as const.
59. Can an operator member function be virtual?
It is possible to declare an operator member function to be virtual, because the mechanics of invoking a member operator function and a regular member function are the same.
60. Can an assignment operator function be declared as friend?
No, an assignment operator can be declared only as a member function, never as a friend.
61. Can a constructor be declared as static?
A static member function can be used without referring to a specific object, using only a class name. They have no ‗this‘ pointer, so they cannot access class member data unless they are passed a ‗this‘ pointer explicitly.
We can't declare constructors to be static. If a constructor was allowed to be static, it could be invoked without a ‗this‘ pointer and therefore would not be able to build specific objects from raw storage.
62. List out the differences between the constructors and destructors
Ø destructors can be virtual whereas constructors can‘t,
Ø you cannot pass arguments to destructors,
Ø there can be one destructor can be declared for a given class,
Ø constructors cannot be called explicitly like the way a normal function is called using their qualified name whereas a destructor can be.
63. Describe some unique features of constructors and destructors.
1. They do not have return value declaration.
2. They cannot be inherited.
3. Their addresses cannot be extracted.
64. What are the situations under which a copy constructor is used?
Ø When a new object is initialized to an object of the same class.
Ø When an object is passed to a function by value.
Ø When a function returns an object by value.
Ø When the compiler generates a temporary object.
65. What are candidate functions?
Let us consider that we have a set of overloaded functions. The set of all these functions are known as candidate functions, because whenever a overloaded function is met in the program they are the candidates for that particular function invocation. In other words, they are the set of functions considered for a resolving a function call. For example:
void f();
void f(int){/*do something*/};
void f(double){ /*do something*/};
void main(){
f(5.6);
}
In this example the functions f() ,f(int) and f(double) are the candidate functions .
66. What are viable functions?
Viable functions are the ones that can possibly be resolved into a function call; they are a subset of candidate functions. For example:
void f();
void f(short){/*do something*/};
void f(double){ /*do something*/};
void main(){
f(5.6);// two viable functions f(short) and f(double).
}
In this case there are 2 viable functions f(short) and f(double), because we can have a standard conversion by which float can be converted to an short or float getting promoted to type double by promotion. But in this case the value 5.6 is promoted to a value of type double and is passed to that function.
67. When is the bad_alloc exception thrown?
We know that ‗new‘ operator is used to allocate space for new objects. If the new operator could not find the space needed to allocate memory for the object, then the allocator throws a bad_alloc exception.
68. 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.
69. Which operators are called as insertion and extraction operators? Why?
The C++ operator >> is called the extraction operator, used to extract characters from an input stream and the operator << is called the insertion operator, used to extract text into an output stream.
70. List out the iostream manipulators
Dec -- Display a numeric values in decimal notation.
endl -- Output a newline char and flush the stream
ends -- Output a null character
flush -- Flush the stream buffer
hex -- Display numeric values in hexadecimal notation
oct -- Display numeric values in octal notation
ws -- Skip over leading white space.
71. 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.
72. List some characteristics of templates that macros do not have.
As opposed to macros, templates:
Ø have linkage for their instantiations,
Ø obey scoping rules (template maybe visible only inside a namespace),
Ø Templates can be overloaded or specialized,
Ø there can be pointers to function template specializations,
Ø can be recursive.
73. What is the use of ‗autoptr‘ template?
Each use of ‗new‘ should be paired with a use of ‗delete‘. This can lead to problems if a function in which new is used terminates early through an exception being thrown. Using an autoptr object to keep track of an object created by automates the activation of delete.
Example:
void model(string &str)
{
string *ps=new string(str);
..........
if(weird_thing())
throw exception();
str=*ps;
delete ps;
return;
}
If the exception is thrown, the delete statement isn't reached and there is a memory leak. The auto_ptr template defines a pointer-like object that is intended to be assigned an address obtained by new. When an auto_ptr object expires, its destructor uses delete to free the memory.
To create an auto_ptr object, include the memory header file, which includes the auto_ptr template. The template includes the following:
templateclass auto_ptr{
public:
explicit auto_ptr(x *p=0) throw();
.......};
Thus asking for an auto_ptr of type x gives you an auto_ptr of type x.
auto_ptrpd(new double); //auto_ptr to double
auto_ptrps(new string); //auto_ptr to string
74. How would you classify friends to templates.
Ø Non template friends.
Ø Bound template friends, meaning that the type of the class determines the type of the friend when a class is instantiated.
Ø Unbound template friends, meaning that all instantiations of the friend are friends to each instantiation of the class.
75. Differentiate between a template class and class template.
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.
76. What is meant by template specialization?
Some cases the general template definition may not fit for a particular data type. For example, let us consider a situation where we are writing a generic function for comparing two values.
Example:
template T max (T t1,T t2) {
return T1>T2?T1:T2;
}
But this template definition won‘t suit for character strings. So we must have a separate function which implements this function for character strings.
template char * max(char * a,char *b ){
return ( strcmp(a,b,)>0?a:b);
}
77. What are Iterators in STL?
Iterators are generalized pointers that may be used to traverse through the contents of a sequence (for example, an STL container or a C++ array). Iterators provide data access for both reading and writing data in a sequence. They serve as intermediaries between containers and generic algorithms. A C++ pointer is an iterator, but an iterator is not necessarily a C++ pointer. Iterators, like pointers can be dereferenced, incremented and decremented. At any point in time, an iterator is positioned at exactly one place in one collection, and remains positioned there until explicitly moved.
Container Classes Generic Algorithms
Iterator
78. How does the allocation of space take place in a vector?
Initially the size and capacity of a vector are initialized to 0 during declaration. On inserting the first element, the capacity increases to 256, if the vector‘s elements are of integer type, 128 if they are of type double, 85 if the elements are of type string. As for as classes are concerned, the capacity after initial insertion is 1, because the size and processing needed for copying or creating a new object of a class is comparatively higher than that for all the above said types. The size of a vector doubles with each reallocation. For example for a vector of type int, during the first reallocation the size allocated is 512 bytes and during the next reallocation it grows to 1024 and so on.
79. 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.
80. What is 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. For example:
class ExpObj
{
private:
int Errno;
public:
ExpObj(int Eno):Errno(Eno) {};
void ShowError()
{
cout << "The error number is " <<0 || y<0)
throw ExpObj(200);
int s = x+y;
cout << "Sum "<


Reblog this post [with Zemanta]

0 comments:

Post a Comment