Upload
sainath-reddy-rajanala
View
126
Download
7
Tags:
Embed Size (px)
Citation preview
1. void main()
{
int d=5;
printf("%f",d);
}Ans: Undefined
2. 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
3. void main()
{
char *s="\12345s\n";
printf("%d",sizeof(s));
}Ans: 6
4. 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<j)
printf("less");
else
if(i>j)
printf("greater");
else
if(i==j)
printf("equal");
}Ans: less
5. void main()
{
float j;
j=1000*1000;
printf("%f",j);
}
1. 1000000
2. Overflow
3. Error
4. None
Ans: 4
6. 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:
7. 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... */
8. 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.)
9. A structure pointer is defined of the type time . With 3 fields min,sec hours
having pointers to integers.
Write the way to initialize the 2nd element to 10.
10. In the above question an array of pointers is declared. Write the statement to
initialize the 3rd element of the 2 element to 10
11. 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);
}What are the number of syntax errors in the above?
Ans: None.
12. void main()
{
int i=7;
printf("%d",i++*i++);
}Ans: 56
13. #define one 0
#ifdef one
printf("one is defined ");
#ifndef one
printf("one is not defined ");
Ans: "one is defined"
14. void main()
{
intcount=10,*temp,sum=0;
temp=&count;
*temp=20;
temp=∑
*temp=count;
printf("%d %d %d ",count,*temp,sum);
}
Ans: 20 20 20
15. There was question in c working only on unix machine with pattern matching.
16. what is alloca() Ans : It allocates and frees memory after use/after getting out of
scope
17. main()
{
static i=3;
printf("%d",i--);
return i>0 ? main():0;
}
Ans: 321
18. 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.
19. 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"
1. Difference b/n scanf("%s",msg);and scanf("%[\^n]",msg); where msg is a char array. 2. What is ure of comma operator in for loop.3. int shw(int *a){ *a = 10; /* return stmt is missing */
} main(){ int p=3,q=4; q = shw(&p); printf("%d %d",p,q); } 4. which is true a. all automatic variables are declared with in the function b. all variables are automatic c. all not declared variables are automatic d. none 5. What is recursion. Recursive prog to generate Fibonacci series . Is it a best method? 6. write 7*a interms of +,-,<< 7. count number of 1's in a 32 bit integer.(i had not remembered whether array or integer). 8. main(){char *s1 = "hello",*s2 ="abce";strcpy(s1,""); s2[0] = s1[0]; printf("%d%d",strlen(s1),strlen(s2)); } 9. regarding memset 10.Algorithm to delete a node in Double linked list. 11. Difference b/n fgets,fscanf which u will prefer. Unix11.What is creon and whats diff b/n 'at' command. 12. what is system call and lib function. whats diff b/n them. abt execve - expalin. 13.some thing abt makeall 14. write abt TCP,IP,ICMP
What are the major differences between C and C++?
What are the differences between new and malloc?
What is the difference between delete and delete[?
What are the differences between a struct in C and in C++?
What are the advantages/disadvantages of using #define?
What are the advantages/disadvantages of using inline and const?
What is the difference between a pointer and a reference?
When would you use a pointer? A reference?
What does it mean to take the address of a reference?
What does it mean to declare a function or variable as static?
What is the order of initialization for data?
What is name mangling/name decoration?
What kind of problems does name mangling cause?
How do you work around them?
What is a class ?
What are the differences between a struct and a class in C++?
What is the difference between public, private, protected, and friend access?
For class CFoo { }; what default methods will the compiler generate for you>?
How can you force the compiler to not generate them?
What is the purpose of a constructor? Destructor?
What is a constructor initializer list?
When must you use a constructor initializer list?
What is a:* Constructor?* Destructor?* Default constructor?* Copy constructor?* Conversion constructor?
What does it mean to declare a...* member function as virtual?* member function as static?* member variable as static?* destructor as static?
Explain the term "resource acquisition is initialization?"
What is a "pure virtual" member function?
What is the difference between public, private, and protected inheritance?
What is virtual inheritance?
What is placement new?
What is the difference between operator new and the new operator?
What is exception handling?
Explain what happens when an exception is thrown in C++.
What happens if an exception is not caught?
What happens if an exception is throws from an object's constructor?
What happens if an exception is throws from an object's destructor?
What are the costs and benefits of using exceptions?
When would you choose to return an error code rather than throw an exception?
What is a template?
What is partial specialization or template specialization?
How can you force instantiation of a template?
What is an iterator?
What is an algorithm (in terms of the STL/C++ standard library)?
What is std::auto_ptr?
What is wrong with this statement?
std::auto_ptr ptr(new char[10]);It is possible to build a C++ compiler on top of a C compiler. How would you do this?
Basic Questions* What is a friend, and why do you need it?* If this doesn't compile, why didn't it (or will it compile?) Don't show comments, which explain the problem.
template void HashTable <>::dummy(){K* k = NULL;Hashable* h = k; // If this fails to compile, it's because// K is not derived from Hashable.}
* This will loop forever. Why? Will it really loop forever? (Answer: Base:func() does not call Base::func(). Base: is just a label, so the line always will call Derived::func() until it runs out of stack space)class Base {public:Base() {}virtual void func() { /* do something */ }};
class Derived : public Base {public:Derived() {}virtual void func(){Base:func();/* do something else */}};main(){Derived d;
d.func(); // Never returns!}
More advanced questions :
* What is a vtbl ?* What is RTTI and why do you need it?* How do I specialize a template? Give an example.To separate sheep from goats (for those claiming C++ Guru status):* What is a partial template? Why would you use one?* How to I create a binary functor in the STL?Given the following code:class A;class B;class C {A* a_;B* b_;public:};
Implement a copy constructor and assignment operator for C. A sample solution is something like:class C {A* a_;B* b_;void swap(C& rhs) { rhs.a_ = a_; rhs.b_ = b_; }public:C(const C& rhs) {auto_ptr<> a(new A(rhs.a_));auto_ptr<> b(new B(rhs.b_)):delete a_;delete b_;a_ = a.release();b_ = b.release();}C& operator=(const C& rhs) {C temp(rhs);temp.swap(*this);return *this;}};
What is wrong with this class, assuming that this is its complete interface?
class C {char *p;public:C() { p = new char[64]; strcpy(p, "Hello world"); }~C() { delete p; }void foo() { cout << "My ptr is: '" << p << "'" << endl; }};
Since this has an overtly programmed destructor, the member wise semantics for destruction are not good enough; therefore, they are not good enough for copy and assignment either. But, the copy ctor and op= are not programmed, so we will have some serious trouble.Gradual hinting: what happens when we make a copy? [correct answer: pointer is copied]. Now, the original goes out of scope, what happens to the copy? [pointer dangles]. How would you fix it?[also, that delete p should be delete[ p since p was allocated with the array new]Assuming that swap() and copy construction are part of your interface for class C, what's the cookie-cutter pattern for operator= that uses them?answer:
C& C:perator=(const C &rhs) {if (this != &rhs) {C tmp(rhs);this->swap(tmp);}return *this;}]]
Amazon->written test. They concentrate on every field of computer science . They asked c,data structure,TOC(context free and context sensitive grammar,regular languages). DBMS unix was not there.There were two subjective questions.1. The first one was "given two lists write a function which returns a list which is the intersection of the two lists.the original lists should remain same. (Intersection - if first list is say,1,20 3,45 and second list is 3,24 ,45,90,68 then intersection should be 3,45 )2. The second was given two nodes of a binary tree find the closest ancestor
of the two nodes.Note:consider binary tree and binary search tree also.In short answer type questions, the questions were - 1.There was an aptitude's question in which P(A) and P(B) were given and we had to find P(B/A) and P(A/B) when A and B are independent events.2.What is the probability that the the 4 digit's no. which is formed by using the digits 1,2,3,4,5,6 is divisible by 4.3.What tree traversal gives the no. in sorted order. Inorder, preorder or postorder ?4.Preorder and inorder traversal was given and we had to find the tree.5. Which sorting algorithm takes best and worst time complexity as O(nlogn)?6.A dbms query was asked to find the second largest no. o
1. Can we declare a static function as virtual?Ans: No. The virtual function mechanism is used on the specific object that determines which virtual function to call. Since the static functions are not any way related to objects, they cannot be declared as virtual.
2. Can user-defined object be declared as static data member of another class ?Ans: Yes. The following code shows how to initialize a user-defined object. #include class test { int i ; public : test ( int ii = 0 ) { i = ii ; } } ; class sample
{ static test s ; } ; test sample::s ( 26 ) ;Here we have initialized the object s by calling the one-argument constructor. Wecan use the same convention to initialize the object by calling multiple-argument constructor.
3. What is forward referencing and when should it be used?Ans: Consider the following program : class test { public : friend void fun ( sample, test ) ; } ; class sample { public : friend void fun ( sample, test ) ; } ; void fun ( sample s, test t ) { // code } void main( ) { sample s ; test t ; fun ( s, t ) ; }This program would not compile. It gives an error that sample is undeclared identifier in the statement friend void fun ( sample, test ) ; of the class test. This is so because the class sample is defined below the class test and we are using it before its definition. To overcome this error we need to give forward reference of the class sample before the definition of class test. The following statement is the forward reference of class sample. Forward referencing is generally required when we make a class or a function as a friend.
4. The istream_withassign class has been derived from the istream class and overloaded assignment operator has been added to it. The _withassign classes are much like their base classes except that they include overloaded assignment operators. Using these operators the objects of the _withassign classes can be copied. The istream, ostream, and iostream classes are made uncopyable by making their overloaded copy constructor and assignment operators private.
5. How do I write my own zero-argument manipulator that should work same as hex?Ans: This is shown in following program.
#include ostream& myhex ( ostream &o ) { o.setf ( ios::hex) ; return o ; } void main( ) { cout << endl << myhex << 2000 ; }
6.We all know that a const variable needs to be initialized at the time of declaration. Then how come the program given below runs properly even when we have not initialized p? #include void main( ) { const char *p ; p = "A const pointer" ; cout << p ; }Ans: The output of the above program is 'A const pointer'. This is because in this program p is declared as 'const char*' which means that value stored at p will be constant and not p and so the program works properly
7. How do I refer to a name of class or function that is defined within a namespace?Ans: There are two ways in which we can refer to a name of class or function that is defined within a namespace: Using scope resolution operator through the using keyword. This is shown in following example:
namespace name1 { class sample1 { // code } ; } namespace name2 { class sample2 { // code } ; } using namespace name2 ; void main( )
{ name1::sample1 s1 ; sample2 s2 ; }Here, class sample1 is referred using the scope resolution operator. On the other hand we can directly refer to class sample2 because of the statement using namespace name2 ; the using keyword declares all the names in the namespace to be in the current scope. So we can use the names without any qualifiers.
8. While overloading a binary operator can we provide default values?Ans: No!. This is because even if we provide the default arguments to the parameters of the overloaded operator function we would end up using the binary operator incorrectly. This is explained in the following example:
sample operator + ( sample a, sample b = sample (2, 3.5f ) ) { } void main( ) { sample s1, s2, s3 ; s3 = s1 + ; // error }
9. How do I carry out conversion of one object of user-defined type to another?Ans: To perform conversion from one user-defined type to another we need to provide conversion function. Following program demonstrates how to provide such conversion function. class circle { private : int radius ; public: circle ( int r = 0 ) { radius = r ; } } ; class rectangle { private : int length, breadth ; public : rectangle( int l, int b ) { length = l ; breadth = b ;
} operator circle( ) { return circle ( length ) ; } } ; void main( ) { rectangle r ( 20, 10 ) ; circle c; c = r ; }Here, when the statement c = r ; is executed the compiler searches for an overloaded assignment operator in the class circle which accepts the object of type rectangle. Since there is no such overloaded assignment operator, the conversion operator function that converts the rectangle object to the circle object is searched in the rectangle class. We have provided such a conversion function in the rectangle class. This conversion operator function returns a circle object. By default conversion operators have the name and return type same as the object type to which it converts to. Here the type of the object is circle and hence the name of the operator function as well as the return type is circle.
10. How do I write code that allows to create only one instance of a class?Ans: This is shown in following code snippet.
#include class sample { static sample *ptr ; private: sample( ) { } public: static sample* create( ) { if ( ptr == NULL ) ptr = new sample ; return ptr ; } } ; sample *sample::ptr = NULL ; void main( ) { sample *a = sample::create( ) ; sample *b = sample::create( ) ; }
Here, the class sample contains a static data member ptr, which is a pointerto the object of same class. The constructor is private which avoids us from creating objects outside the class. A static member function called create( ) is used to create an object of the class. In this function the condition is checked whether or not ptr is NULL, if it is then an object is created dynamically and its address collected in ptr is returned. If ptr is not NULL, then the same address is returned. Thus, in main( ) on execution of the first statement one object of sample gets created whereas on execution of second statement, b holds the address of the first object. Thus, whatever number of times you call create( ) function, only one object of sample class will be available.
11. How do I write code to add functions, which would work as get and put properties of a class?Ans: This is shown in following code. #include class sample { int data ; public: __declspec ( property ( put = fun1, get = fun2 ) ) int x ; void fun1 ( int i ) { if ( i < 0 ) data = 0 ; else data = i ; } int fun2( ) { return data ; } } ; void main( ) { sample a ; a.x = -99 ; cout << a.x ; }Here, the function fun1( ) of class sample is used to set the given integer value into data, whereas fun2( ) returns the current value of data. To set these functions as properties of a class we have given the statement as shown below:__declspec ( property ( put = fun1, get = fun2 )) int x ;
As a result, the statement a.x = -99 ; would cause fun1( ) to get called to set the value in data. On the other hand, the last statement would cause fun2( ) to get called to return the value of data.
12. How do I write code to make an object work like a 2-D array?Ans: Take a look at the following program. #include class emp { public : int a[3][3] ; emp( ) { int c = 1 ; for ( int i = 0 ; i <= 2 ; i++ ) { for ( int j = 0 ; j <= 2 ; j++ ) { a[i][j] = c ; c++ ; } } } int* operator[] ( int i ) { return a[i] ; } } ; void main( ) { emp e ; cout << e[0][1] ; }The class emp has an overloaded operator [ ] function. It takes one argument an integer representing an array index and returns an int pointer. The statement cout << e[0][1] ; would get converted into a call to the overloaded [ ] function as e.operator[ ] ( 0 ). 0 would get collected in i. The function would return a[i] that represents the base address of the zeroeth row. Next the statement would get expanded as base address of zeroeth row[1] that can be further expanded as *( base address + 1 ). This gives us a value in zeroth row and first column.
13. What are formatting flags in ios class?Ans: The ios class contains formatting flags that help users to format the stream data. Formatting flags are a set of enum definitions. There are two types of formatting flags: On/Off flags Flags that work in-groupThe On/Off flags are turned on using the setf( ) function and are turned off using the unsetf( ) function. To set the On/Off flags, the one argument setf( ) function is used. The flags working in groups are set through the two-argument setf( ) function. For example, to left justify a string we can set the flag as,
cout.setf ( ios::left ) ; cout << "KICIT Nagpur" ; To remove the left justification for subsequent output we can say, cout.unsetf ( ios::left ) ;The flags that can be set/unset include skipws, showbase, showpoint,uppercase, showpos, unitbuf and stdio. The flags that work in a group can have only one of these flags set at a time.
14. What is the purpose of ios::basefield in the following statement? cout.setf ( ios::hex, ios::basefield ) ;Ans: This is an example of formatting flags that work in a group. There is a flag for each numbering system (base) like decimal, octal and hexadecimal. Collectively, these flags are referred to as basefield and are specified by ios::basefield flag. We can have only one of these flags on at a time. If we set the hex flag as setf ( ios::hex ) then we will set the hex bit but we won't clear the dec bit resulting in undefined behavior. The solution is to call setf( ) as setf ( ios::hex, ios::basefield ). This call first clears all the bits and then sets the hex bit.
15. Can we get the value of ios format flags?Ans: Yes! The ios::flags( ) member function gives the value format flags. This function takes no arguments and returns a long ( typedefed to fmtflags) that contains the current format flags.
16. Is there any function that can skip certain number of characters present in the input stream?Ans: Yes! This can be done using cin::ignore( ) function. The prototype of this function is as shown below: istream& ignore ( int n = 1, int d =EOF ) ;Sometimes it happens that some extra characters are left in the input stream while taking the input such as, the ?\n? (Enter) character. This extra character is then passed to the next input and may pose problem.
To get rid of such extra characters the cin::ignore( ) function is used. This is equivalent to fflush ( stdin ) used in C language. This function ignores the first n characters (if present) in the input stream, stops if delimiter d is encountered.
17. Write a program that implements a date class containing day, month and year as data members. Implement assignment operator and copy constructor in this class.Ans: This is shown in following program: #include class date { private : int day ; int month ; int year ;
public : date ( int d = 0, int m = 0, int y = 0 ) { day = d ; month = m ; year = y ; } // copy constructor date ( date &d ) { day = d.day ; month = d.month ; year = d.year ; } // an overloaded assignment operator date operator = ( date d ) { day = d.day ; month = d.month ; year = d.year ; return d ; } void display( ) { cout << day << "/" << month << "/" << year ; } } ; void main( ) { date d1 ( 25, 9, 1979 ) ; date d2 = d1 ; date d3 ; d3 = d2 ; d3.display( ) ; }
18. When should I use unitbuf flag?Ans: The unit buffering (unitbuf) flag should be turned on when we want to ensure that each character is output as soon as it is inserted into an output stream. The same can be done using unbuffered output but unit buffering provides a better performance than the unbuffered output.
19.What are manipulators?Ans: Manipulators are the instructions to the output stream to modify the output in various ways. The manipulators provide a clean and easy way for formatted output in comparison to the formatting flags of the ios class. When manipulators are used, the
formatting instructions are inserted directly into the stream. Manipulators are of two types, those that take an argument and those that don?t.
20. What is the difference between the manipulator and setf( ) function?Ans: The difference between the manipulator and setf( ) function are as follows:
The setf( ) function is used to set the flags of the ios but manipulators directly insert the formatting instructions into the stream. We can create user-defined manipulators but setf( ) function uses data members of ios class only. The flags put on through the setf( ) function can be put off through unsetf( ) function. Such flexibility is not available with manipulators.
21. How do I get the current position of the file pointer?Ans: We can get the current position of the file pointer by using the tellp( ) member function of ostream class or tellg( ) member function of istream class. These functions return (in bytes) positions of put pointer and get pointer respectively.
22. What are put and get pointers?Ans: These are the long integers associated with the streams. The value present in the put pointer specifies the byte number in the file from where next write would take place in the file. The get pointer specifies the byte number in the file from where the next reading should take place.
23. What do the nocreate and noreplace flag ensure when they are used for opening a file?Ans: nocreate and noreplace are file-opening modes. A bit in the ios class defines these modes. The flag nocreate ensures that the file must exist before opening it. On the other hand the flag noreplace ensures that while opening a file for output it does not get overwritten with new one unless ate or app is set. When the app flag is set then whatever we write gets appended to the existing file. When ate flag is set we can start reading or writing at the end of existing file.
24. What is the limitation of cin while taking input for character array?Ans: To understand this consider following statements, char str[5] ; cin >> str ;While entering the value for str if we enter more than 5 characters then there is no provision in cin to check the array bounds. If the array overflows, it may be dangerous. This can be avoided by using get( ) function. For example, consider following statement, cin.get ( str, 5 ) ;On executing this statement if we enter more than 5 characters, then get( ) takes only first five characters and ignores rest of the characters. Some more variations of get( ) are available, such as shown below: get ( ch ) ? Extracts one character only get ( str, n ) ? Extracts up to n characters into str get ( str, DELIM ) ? Extracts characters into array str until specified delimiter (such as
'\n'). Leaves delimiting character in stream. get ( str, n, DELIM ) ? Extracts characters into array str until n characters or DELIM character, leaving delimiting character in stream.
25. What is the purpose of istream class? Ans: The istream class performs activities specific to input. It is derived from the ios class. The most commonly used member function of this class is the overloaded >> operator which can extract values of all basic types. We can extract even a string using this operator.
26. Would the following code work? #include void main( ) { ostream o ; o << "Dream. Then make it happen!" ; }Ans: No! This is because we cannot create an object of the ostream class since its constructor and copy constructor are declared private.
27. Can we use this pointer inside static member function?Ans: No! The this pointer cannot be used inside a static member function. This is because a static member function is never called through an object.
28. What is strstream?Ans: strstream is a type of input/output stream that works with the memory. It allows using section of the memory as a stream object. These streams provide the classes that can be used for storing the stream of bytes into memory. For example, we can store integers, floats and strings as a stream of bytes. There are several classes that implement this in-memory formatting. The class ostrstream derived from ostream is used when output is to be sent to memory, the class istrstream derived from istream is used when input is taken from memory and strstream class derived from iostream is used for memory objects that do both input and output. Ans: When we want to retrieve the streams of bytes from memory we can use istrestream. The following example shows the use of istrstream class. #include void main( ) { int age ; float salary ; char name[50] ; char str[] = "22 12004.50 K. Vishwanatth" ; istrstream s ( str ) ; s >> age >> salary >> name ; cout << age << endl << salary << endl << name ; cout << endl << s.rdbuf( ) ;
}Here, s is the object of the class istrstream. When we are creating the object s, the constructor of istrstream gets called that receives a pointer to the zero terminated character array str. The statement s >> age >> salary >> name ; extracts the age, salary and the name from the istrstream object s. However, while extracting the name, only the first word of name gets extracted. The balance is extracted using rdbuf( ).
29. When the constructor of a base class calls a virtual function, why doesn't the override function of the derived class gets called?Ans: While building an object of a derived class first the constructor of the base class and then the constructor of the derived class gets called. The object is said an immature object at the stage when the constructor of base class is called. This object will be called a matured object after the execution of the constructor of the derived class. Thus, if we call a virtual function when an object is still immature, obviously, the virtual function of the base class would get called. This is illustrated in the following example. #include class base { protected : int i ; public : base ( int ii = 0 ) { i = ii ; show( ) ; } virtual void show( ) { cout << "base's show( )" << endl ; } } ; class derived : public base { private : int j ; public : derived ( int ii, int jj = 0 ) : base ( ii ) { j = jj ; show( ) ; } void show( ) { cout << "derived's show( )" << endl ; } } ;
void main( ) { derived dobj ( 20, 5 ) ; } The output of this program would be: base's show( ) derived's show( )
30. Can I have a reference as a data member of a class? If yes, then how do I initialise it?Ans: Yes, we can have a reference as a data member of a class. A reference as a data member of a class is initialized in the initialization list of the constructor. This is shown in following program. #include class sample { private : int& i ; public : sample ( int& ii ) : i ( ii ) { } void show( ) { cout << i << endl ; } } ; void main( ) { int j = 10 ; sample s ( j ) ; s.show( ) ; }Here, i refers to a variable j allocated on the stack. A point to note here is that we cannot bind a reference to an object passed to the constructor as a value. If we do so, then the reference i would refer to the function parameter (i.e. parameter ii in the constructor), which would disappear as soon as the function returns, thereby creating a situation of dangling reference.
31. Why does the following code fail? #include class sample { private : char *str ; public : sample ( char *s )
{ strcpy ( str, s ) ; } ~sample( ) { delete str ; } } ; void main( ) { sample s1 ( "abc" ) ; }Ans: Here, through the destructor we are trying to deal locate memory, which has been allocated statically. To remove an exception, add following statement to the constructor. sample ( char *s ) { str = new char[strlen(s) + 1] ; strcpy ( str, s ) ; }Here, first we have allocated memory of required size, which then would get deal located through the destructor.
32. assert( ) macro...We can use a macro called assert( ) to test for conditions that should not occur in a code. This macro expands to an if statement. If test evaluates to 0, assert prints an error message and calls abort to abort the program. #include #include void main( ) { int i ; cout << "\nEnter an integer: " ; cin >> i ; assert ( i >= 0 ) ; cout << i << endl ; }
33. Why it is unsafe to deal locate the memory using free( ) if it has beenallocated using new?Ans: This can be explained with the following example: #include class sample { int *p ; public : sample( )
{ p = new int ; } ~sample( ) { delete p ; } } ; void main( ) { sample *s1 = new sample ; free ( s1 ) ; sample *s2 = ( sample * ) malloc ( sizeof ( sample ) ) ; delete s2 ; }The new operator allocates memory and calls the constructor. In the constructor we have allocated memory on heap, which is pointed to by p. If we release the object using the free( ) function the object would die but the memory allocated in the constructor would leak. This is because free( ) being a C library function does not call the destructor where we have deal located the memory.
As against this, if we allocate memory by calling malloc( ) the constructor would not get called. Hence p holds a garbage address. Now if the memory is deal located using delete, the destructor would get called where we have tried to release the memory pointed to by p. Since p contains garbage this may result in a runtime error.
34. Can we distribute function templates and class templates in object libraries?Ans: No! We can compile a function template or a class template into object code (.obj file). The code that contains a call to the function template or the code that creates an object from a class template can get compiled. This is because the compiler merely checks whether the call matches the declaration (in case of function template) and whether the object definition matches class declaration (in case of class template). Since the function template and the class template definitions are not found, the compiler leaves it to the linker to restore this. However, during linking, linker doesn't find the matching definitions for the function call or a matching definition for object creation. In short the expanded versions of templates are not found in the object library. Hence the linker reports error.
35. What is the difference between an inspector and a mutator ?Ans: An inspector is a member function that returns information about an object's state (information stored in object's data members) without changing the object's state. A mutator is a member function that changes the state of an object. In the class Stack given below we have defined a mutator and an inspector. class Stack { public :
int pop( ) ; int getcount( ) ; }In the above example, the function pop( ) removes top element of stack thereby changing the state of an object. So, the function pop( ) is a mutator. The function getcount( ) is an inspector because it simply counts the number of elements in the stack without changing the stack.
36. Namespaces:The C++ language provides a single global namespace. This can cause problems with global name clashes. For instance, consider these two C++ header files: // file1.h float f ( float, int ) ; class sample { ... } ; // file2.h class sample { ... } ;With these definitions, it is impossible to use both header files in a single program; the sample classes will clash. A namespace is a declarative region that attaches an additional identifier to any names declared inside it. The additional identifier thus avoids the possibility that a name will conflict with names declared elsewhere in the program. It is possible to use the same name in separate namespaces without conflict even if the names appear in the same translation unit. As long as they appear in separate namespaces, each name will be unique because of the addition of the namespace identifier. For example: // file1.h namespace file1 { float f ( float, int ) ; class sample { ... } ; } // file2.h namespace file2 { class sample { ... } ; }
Now the class names will not clash because they become file1::sample and file2::sample, respectively.
37. What would be the output of the following program? #include class user { int i ; float f ; char c ; public :
void displaydata( ) { cout << endl << i << endl << f << endl << c ; } } ; void main( ) { cout << sizeof ( user ) ; user u1 ; cout << endl << sizeof ( u1 ) ; u1.displaydata( ) ; }Ans: The output of this program would be, 9 or 7 9 or 7 Garbage Garbage GarbageSince the user class contains three elements, int, float and char its size would be 9 bytes (int-4, float-4, char-1) under Windows and 7 bytes (int-2, float-4, char-1) under DOS. Second output is again the same because u1 is an object of the class user. Finally three garbage values are printed out because i, f and c are not initialized anywhere in the program.
Note that if you run this program you may not get the answer shown here. This is because packing is done for an object in memory to increase the access efficiency. For example, under DOS, the object would be aligned on a 2-byte boundary. As a result, the size of the object would be reported as 6 bytes. Unlike this, Windows being a 32-bit OS the object would be aligned on a 4-byte boundary. Hence the size of the object would be reported as 12 bytes. To force the alignment on a 1-byte boundary, write the following statement before the class declaration. #pragma pack ( 1 )
38. Write a program that will convert an integer pointer to an integer and vice-versa. Ans: The following program demonstrates this. #include void main( ) { int i = 65000 ; int *iptr = reinterpret_cast ( i ) ; cout << endl << iptr ; iptr++ ; cout << endl << iptr ; i = reinterpret_cast ( iptr ) ; cout << endl << i ; i++ ;
cout << endl << i ; }
39. What is a const_cast?Ans. The const_cast is used to convert a const to a non-const. This is shown in the following program: #include void main( ) { const int a = 0 ; int *ptr = ( int * ) &a ; //one way ptr = const_cast_ ( &a ) ; //better way }Here, the address of the const variable a is assigned to the pointer to a non-const variable. The const_cast is also used when we want to change the data members of a class inside the const member functions. The following code snippet shows this: class sample { private: int data; public: void func( ) const { (const_cast (this))->data = 70 ; } } ;
40. What is forward referencing and when should it be used?Ans: Forward referencing is generally required when we make a class or a function as a friend.Consider following program: class test { public: friend void fun ( sample, test ) ; } ; class sample { public: friend void fun ( sample, test ) ; } ; void fun ( sample s, test t ) { // code }
void main( ) { sample s ; test t ; fun ( s, t ) ; }On compiling this program it gives error on the following statement of test class. It gives an error that sample is undeclared identifier. friend void fun ( sample, test );This is so because the class sample is defined below the class test and we are using it before its definition. To overcome this error we need to give forward reference of the class sample before the definition of class test. The following statement is the forward reference of class sample. class sample ;
41. How would you give an alternate name to a namespace?Ans: An alternate name given to namespace is called a namespace-alias. namespace-alias is generally used to save the typing effort when the names of namespaces are very long or complex. The following syntax is used to give an alias to a namespace. namespace myname = my_old_very_long_name ;
42. Using a smart pointer can we iterate through a container?Ans: Yes. A container is a collection of elements or objects. It helps to properly organize and store the data. Stacks, linked lists, arrays are examples of containers. Following program shows how to iterate through a container using a smart pointer. #include class smartpointer { private : int *p ; // ordinary pointer public : smartpointer ( int n ) { p = new int [ n ] ; int *t = p ; for ( int i = 0 ; i <= 9 ; i++ ) *t++ = i * i ; } int* operator ++ ( int ) { return p++ ; } int operator * ( ) { return *p ; } } ;
void main( ) { smartpointer sp ( 10 ) ; for ( int i = 0 ; i <= 9 ; i++ ) cout << *sp++ << endl ; }Here, sp is a smart pointer. When we say *sp, the operator * ( ) function gets called. It returns the integer being pointed to by p. When we say sp++ the operator ++ ( ) function gets called. It increments p to point to The next element in the array and then returns the address of this new location.
43. Can objects read and write themselves?Ans: Yes! This can be explained with the help of following example: #include #include class employee { private : char name [ 20 ] ; int age ; float salary ; public : void getdata( ) { cout << "Enter name, age and salary of employee : " ; cin >> name >> age >> salary ; } void store( ) { ofstream file ; file.open ( "EMPLOYEE.DAT", ios::app | ios::binary ) ; file.write ( ( char * ) this, sizeof ( *this ) ) ; file.close( ) ; } void retrieve ( int n ) { ifstream file ; file.open ( "EMPLOYEE.DAT", ios:
1. In the command scanf, h is used for
Ans. Short int
2. A process is defined as
Ans. Program in execution
3. A thread is
Ans. Detachable unit of executable code)
4. What is the advantage of Win NT over Win 95
Ans. Robust and secure
5. How is memory management done in Win95
Ans. Through paging and segmentation
6. What is meant by polymorphism
Ans. Redfinition of a base class method in a derived class
7. What is the essential feature of inheritance
Ans. All properties of existing class are derived
8. What does the protocol FTP do
Ans. Transfer a file b/w stations with user authentification
9. In the transport layer ,TCP is what type of protocol
Ans. Connection oriented
10. Why is a gateway used
Ans. To connect incompatible networks
11. How is linked list implemented
Ans. By referential structures
12. What method is used in Win95 in multitasking
Ans. Non preemptive check
13. What is meant by functional dependency
14. What is a semaphore
Ans. A method synchronization of multiple processes
15. What is the precedence order from high to low ,of the symbols ( ) ++ /
Ans.( ) , ++, /
16. Preorder of A*(B+C)/D-G
Ans.*+ABC/-DG
17. B-tree (failure nodes at same level)
18. Dense index (index record appers for every search -key in file)
19. What is the efficiency of merge sort
Ans. O(n log n)
20. A program on swaping ( 10,5 )was given (candidate cannot recollect)
21. In which layer are routers used
Ans.In network layer
22. In which layer are packets formed ( in network layer )
23. heap ( priority queue )
24. copy constructor ( constant reference )
25. Which of the following sorting algorithem has average sorting behavior --Bubble
sort,merge sort,heap sort,exchange sort
Ans. Heap sort
26. In binary search tree which traversal is used for getting ascending order values--
Inorder ,post order,preorder
Ans.Inorder
27. What are device drivers used for
Ans.To provide software for enabling the hardware
28. Irrevalent to unix command ( getty)
29. What is fork command in unix
Ans. System call used to create process
30. What is make command in unix
Ans. Used forcreation of more than one file
31. In unix .profile contains
Ans. Start up program
32. In unix echo is used for ( answer C)
33. In unix 'ls 'stores contents in
Ans.inode block
QUANTITATIVE SECTION
1. In a class composed of x girls and y boys what part of the class is composed of
girls
A.y/(x + y)
B.x/xy
C.x/(x + y)
D.y/xy
Ans.C
2. What is the maximum number of half-pint bottles of cream that can be filled with
a 4-gallon can of cream(2 pt.=1 qt. and 4 qt.=1 gal)
A.16
B.24
C.30
D.64
Ans.D
3. If the operation,^ is defined by the equation x ^ y = 2x + y,what is the value of a
in 2 ^ a = a ^ 3
A.0
B.1
C.-1
D.4
Ans.B
4. A coffee shop blends 2 kinds of coffee,putting in 2 parts of a 33p. a gm. grade to
1 part of a 24p. a gm.If the mixture is changed to 1 part of the 33p. a gm. to 2 parts of the
less expensive grade,how much will the shop save in blending 100 gms.
A.Rs.90
B.Rs.1.00
C.Rs.3.00
D.Rs.8.00
Ans.C
5. There are 200 questions on a 3 hr examination.Among these questions are 50
mathematics problems.It is suggested that twice as much time be spent on each maths
problem as for each other question.How many minutes should be spent on mathematics
problems
A.36
B.72
C.60
D.100
Ans.B
6. In a group of 15,7 have studied Latin, 8 have studied Greek, and 3 have not
studied either.How many of these studied both Latin and Greek
A.0
B.3
C.4
D.5
Ans.B
7. If 13 = 13w/(1-w) ,then (2w)2 =
A.1/4
B.1/2
C.1
D.2
Ans.C
8.
1. If a and b are positive integers and (a-b)/3.5 = 4/7, then
(A) b < a
(B) b > a
(C) b = a
(D) b >= a
Ans. A
9. In june a baseball team that played 60 games had won 30% of its game played.
After a phenomenal winning streak this team raised its average to 50% .How many
games must the team have won in a row to attain this average?
A. 12
B. 20
C. 24
D. 30
Ans. C
10. M men agree to purchase a gift for Rs. D. If three men drop out how much more
will each have to contribute towards the purchase of the gift/
A. D/(M-3)
B. MD/3
C. M/(D-3)
D. 3D/(M2-3M)
Ans. D
11. A company contracts to paint 3 houses. Mr.Brown can paint a house in 6 days
while Mr.Black would take 8 days and Mr.Blue 12 days. After 8 days Mr.Brown goes on
vacation and Mr. Black begins to work for a period of 6 days. How many days will it take
Mr.Blue to complete the contract?
A. 7
B. 8
C. 11
D. 12
Ans.C
12. 2 hours after a freight train leaves Delhi a passenger train leaves the same station
travelling in the same direction at an average speed of 16 km/hr. After travelling 4 hrs the
passenger train overtakes the freight train. The average speed of the freight train was?
A. 30
B. 40
C.58
D. 60
Ans. B
13. If 9x-3y=12 and 3x-5y=7 then 6x-2y = ?
A.-5
B. 4
C. 2
D. 8
Ans. D
ANALYTICAL ABILITY
1. The office staff of XYZ corporation presently consists of three bookeepers--A, B, C and
5 secretaries D, E, F, G, H. The management is planning to open a new office in another
city using 2 bookeepers and 3 secretaries of the present staff . To do so they plan to
seperate certain individuals who don't function well together. The following guidelines
were established to set up the new office
I. Bookeepers A and C are constantly finding fault with one another and should not be
sent together to the new office as a team
II. C and E function well alone but not as a team , they should be seperated
III. D and G have not been on speaking terms and shouldn't go together
IV Since D and F have been competing for promotion they shouldn't be a team
1. If A is to be moved as one of the bookeepers,which of the following cannot be a
possible working unit.
A.ABDEH
B.ABDGH
C.ABEFH
D.ABEGH
Ans.B
2. If C and F are moved to the new office,how many combinations are possible
A.1
B.2
C.3
D.4
Ans.A
3. If C is sent to the new office,which member of the staff cannot go with C
A.B
B.D
C.F
D.G
Ans.B
4. Under the guidelines developed,which of the following must go to the new office
A.B
B.D
C.E
D.G
Ans.A
5. If D goes to the new office,which of the following is/are true
I.C cannot go
II.A cannot go
III.H must also go
A.I only
B.II only
C.I and II only
D.I and III only
Ans.D
2.After months of talent searching for an administrative assistant to the president of the
college the field of applicants has been narrowed down to 5--A, B, C, D, E .It was
announced that the finalist would be chosen after a series of all-day group personal
interviews were held.The examining committee agreed upon the following procedure
I.The interviews will be held once a week
II.3 candidates will appear at any all-day interview session
III.Each candidate will appear at least once
IV.If it becomes necessary to call applicants for additonal interviews, no more 1 such
applicant should be asked to appear the next week
V.Because of a detail in the written applications,it was agreed that whenever candidate B
appears, A should also be present.
VI.Because of travel difficulties it was agreed that C will appear for only 1 interview.
1. At the first interview the following candidates appear A,B,D.Which of the
follwing combinations can be called for the interview to be held next week.
A.BCD
B.CDE
C.ABE
D.ABC
Ans.B
2. Which of the following is a possible sequence of combinations for interviews in 2
successive weeks
A.ABC;BDE
B.ABD;ABE
C.ADE;ABC
D.BDE;ACD
Ans.C
3. If A ,B and D appear for the interview and D is called for additional interview the
following week,which 2 candidates may be asked to appear with D?
I. A
II B
III.C
IV.EA.I and II
B.I and III only
C.II and III only
D.III and IV only
Ans.D
4. Which of the following correctly state(s) the procedure followed by the search
committee
I.After the second interview all applicants have appeared at least once
II.The committee sees each applicant a second time
III.If a third session,it is possible for all applicants to appear at least twice
A.I only
B.II only
C.III only
D.Both I and II
Ans.A
A certain city is served by subway lines A,B and C and numbers 1 2 and 3
When it snows , morning service on B is delayed
When it rains or snows , service on A, 2 and 3 are delayed both in the morning and
afternoon
When temp. falls below 30 degrees farenheit afternoon service is cancelled in either the A
line or the 3 line,
but not both.
When the temperature rises over 90 degrees farenheit, the afternoon service is cancelled
in either the line C or the
3 line but not both.
When the service on the A line is delayed or cancelled, service on the C line which
connects the A line, is delayed.
When service on the 3 line is cancelled, service on the B line which connects the 3 line is
delayed.
1. On Jan 10th, with the temperature at 15 degree farenheit, it snows all day. On how
many lines will service be
affected, including both morning and afternoon.
(A) 2
(B) 3
(C) 4
(D) 5
Ans. D
2. of lines on which service will be affected?
(A) 2
(B) 3
(C) 4
(D) 5
Ans. C
3. On which of the following occasions would service be on the greatest number of
lines disrupted.
(A) A snowy afternoon with the temperature at 45 degree farenheit
(B) A snowy morning with the temperature at 45 degree farenheit
(C) A rainy afternoon with the temperature at 45 degree farenheit
(D) A rainy afternoon with the temperature at 95 degree farenheit
Ans. B
In a certain society, there are two marriage groups, red and brown. No marriage is
permitted within a group. On marriage, males become part of their wives groups; women
remain in their own group. Children belong to the same group as their parents.
Widowers and divorced males revert to the group of their birth. Marriage to more than
one person at the same time and marriage to a direct descendant are forbidden
1. A brown female could have had
I. A grandfather born Red
II. A grandmother born Red
III Two grandfathers born Brown
(A) I only
(B) III only
(C) I, II and III
(D) I and II only
Ans. D
2. A male born into the brown group may have
(A) An uncle in either group
(B) A brown daughter
(C) A brown son
(D) A son-in-law born into red group
Ans. A
3. Which of the following is not permitted under the rules as stated.
(A) A brown male marrying his father's sister
(B) A red female marrying her mother's brother
(C) A widower marrying his wife's sister
(D) A widow marrying her divorced daughter's ex-husband
Ans. B
4. If widowers and divorced males retained their group they had upon marrying
which of the following would be permissible ( Assume that no previous marriage
occurred)
(A) A woman marrying her dead sister's husband
(B) A woman marrying her divorced daughter's ex-husband
(C) A widower marrying his brother's daughter
(D) A woman marrying her mother's brother who is a widower.
Ans. D
I. All G's are H's
II. All G's are J's or K's
III All J's and K's are G's
IV All L's are K's
V All N's are M's
VI No M's are G's
1. If no P's are K's which of the following must be true
(A) No P is a G
(B) No P is an H
(C) If any P is an H it is a G
(D) If any P is a G it is a J
Ans. D
2. Which of the following can be logically deduced from the stated conditions
(A) No M's are H's
(B) No H's are M's
(C) Some M's are H's
(D) No N's are G's
Ans. D
3. Which of the following is inconsistent with one or more conditions
(A) All H's are G's
(B) All H's are M's
(C) Some H's are both M's and G's
(D) No M's are H's
Ans. C
4. The statement "No L's are J's" is
I. Logically deducible from the conditions stated
II Consistent with but not deducible from the conditions stated
III. Deducible from the stated conditions together with the additional statements
"No J's are K's"
(A) I only
(B) II only
(C) III only
(D) II and III only
Ans. D