Thursday, May 31, 2007

Tuesday, May 29, 2007

c faqs

1) List object oriented methodologies
2) Name some object oriented languages
3) What are the features of object oriented language
4) What is method overloading
5) What is method overriding
6) When would one define a static variable / global variable ? Difference between them?
7) What is Default constructor?
8) What is Copy constructor?
9) What is Conversion constructor?
10) Difference between method and message?
11) Difference between C++ Struct and C++ class?
12) What is an abstract class?
13) What is pure virtual class?
14) What do you understand by namescape?
15) What is Virtual Destructor?
16) What is the diff between "new" and "operator new" ?
17) What is operator overloading? What operators can be overloaded?
18) What does static variable mean?
19) What is static identifier?
20) What is a pointer?
21) What is a reference?
22) Difference between pointer and reference?
23) What is a structure?
24) What are the differences between structures and arrays?
25) What is difference between pass by value and pass by reference?
26) What are the differences between malloc() and calloc()?
27) What are macros?
28) What are the advantages and disadvantages of macros?
29) What are templates?
30) Difference between template and macros?
31) Difference between arrays and linked list?
32) What are enumerations?

faqs 2

C,C++ Interview Questions Part 1

How do you find out if a linked-list has an end? (i.e. the list is not a cycle)

You can find out by using 2 pointers. One of them goes 2 nodes each time. The second one goes at 1 nodes each time. If there is a cycle, the one that goes 2 nodes each time will eventually meet the one that goes slower. If that is the case, then you will know the linked-list is a cycle.

What is the difference between realloc() and free()?

The free subroutine frees a block of memory previously allocated by the malloc subroutine. Undefined results occur if the Pointer parameter is not a valid pointer. If the Pointer parameter is a null value, no action will occur. The realloc subroutine changes the size of the block of memory pointed to by the Pointer parameter to the number of bytes specified by the Size parameter and returns a new pointer to the block. The pointer specified by the Pointer parameter must have been created with the malloc, calloc, or realloc subroutines and not been deallocated with the free or realloc subroutines. Undefined results occur if the Pointer parameter is not a valid pointer.

What is function overloading and operator overloading?

Function overloading: C++ enables several functions of the same name to be defined, as long as these functions have different sets of parameters (at least as far as their types are concerned). This capability is called function overloading. When an overloaded function is called, the C++ compiler selects the proper function by examining the number, types and order of the arguments in the call. Function overloading is commonly used to create several functions of the same name that perform similar tasks but on different data types.

Operator overloading allows existing C++ operators to be redefined so that they work on objects of user-defined classes. Overloaded operators are syntactic sugar for equivalent function calls. They form a pleasant facade that doesn't add anything fundamental to the language (but they can improve understandability and reduce maintenance costs).

What is the difference between declaration and definition?

The declaration tells the compiler that at some later point we plan to present the definition of this declaration.
E.g.: void stars () //function declaration
The definition contains the actual implementation.
E.g.: void stars () // declarator
{
for(int j=10; j > =0; j--) //function body
cout << *; cout <<>

What are the advantages of inheritance?

It permits code reusability. Reusability saves time in program development. It encourages the reuse of proven and debugged high-quality software, thus reducing problem after a system becomes functional.

How do you write a function that can reverse a linked-list?

void reverselist(void)
{
if(head==0)
return;
if(head->next==0)
return;
if(head->next==tail)
{
head->next = 0;
tail->next = head;
}
else
{
node* pre = head;
node* cur = head->next;
node* curnext = cur->next;
head->next = 0;
cur-> next = head;

for(; curnext!=0; )
{
cur->next = pre;
pre = cur;
cur = curnext;
curnext = curnext->next;
}
curnext->next = cur;
}
}

What do you mean by inline function?

The idea behind inline functions is to insert the code of a called function at the point where the function is called. If done carefully, this can improve the application's performance in exchange for increased compile time and possibly (but not always) an increase in the size of the generated binary executables.

Write a program that ask for user input from 5 to 9 then calculate the average

#include "iostream.h"
int main() {
int MAX = 4;
int total = 0;
int average;
int numb;
for (int i=0; icout << "Please enter your input between 5 and 9: "; cin >> numb;
while ( numb<5>9) {
cout << "Invalid input, please re-enter: "; cin >> numb;
}
total = total + numb;
}
average = total/MAX;
cout << "The average number is: " <<>return 0;
}

What is public, protected, private?

  • Public, protected and private are three access specifiers in C++.
  • Public data members and member functions are accessible outside the class.
  • Protected data members and member functions are only available to derived classes.
  • Private data members and member functions can’t be accessed outside the class. However there is an exception can be using friend classes.
Write a function that swaps the values of two integers, using int* as the argument type.
void swap(int* a, int*b) {
int t;
t = *a;
*a = *b;
*b = t;
}

Tell how to check whether a linked list is circular.

Create two pointers, each set to the start of the list. Update each as follows:
while (pointer1) {
pointer1 = pointer1->next;
pointer2 = pointer2->next; if (pointer2) pointer2=pointer2->next;
if (pointer1 == pointer2) {
print (\"circular\n\");
}
}

OK, why does this work?
If a list is circular, at some point pointer2 will wrap around and be either at the item just before pointer1, or the item before that. Either way, it’s either 1 or 2 jumps until they meet.

What is polymorphism?

Polymorphism is the idea that a base class can be inherited by several classes. A base class pointer can point to its child class and a base class array can store different child class objects.

What is virtual constructors/destructors?

Answer1
Virtual destructors:

If an object (with a non-virtual destructor) is destroyed explicitly by applying the delete operator to a base-class pointer to the object, the base-class destructor function (matching the pointer type) is called on the object.
There is a simple solution to this problem declare a virtual base-class destructor.
This makes all derived-class destructors virtual even though they don’t have the same name as the base-class destructor. Now, if the object in the hierarchy is destroyed explicitly by applying the delete operator to a base-class pointer to a derived-class object, the destructor for the appropriate class is called. Virtual constructor: Constructors cannot be virtual. Declaring a constructor as a virtual function is a syntax error.

Answer2
Virtual destructors: If an object (with a non-virtual destructor) is destroyed explicitly by applying the delete operator to a base-class pointer to the object, the base-class destructor function (matching the pointer type) is called on the object.
There is a simple solution to this problem – declare a virtual base-class destructor. This makes all derived-class destructors virtual even though they don’t have the same name as the base-class destructor. Now, if the object in the hierarchy is destroyed explicitly by applying the delete operator to a base-class pointer to a derived-class object, the destructor for the appropriate class is called.

Virtual constructor: Constructors cannot be virtual. Declaring a constructor as a virtual function is a syntax error.

Does c++ support multilevel and multiple inheritance?
Yes.

What are the advantages of inheritance?
• It permits code reusability.
• Reusability saves time in program development.
• It encourages the reuse of proven and debugged high-quality software, thus reducing problem after a system becomes functional.
What is the difference between declaration and definition?
The declaration tells the compiler that at some later point we plan to present the definition of this declaration.
E.g.: void stars () //function declaration
The definition contains the actual implementation.
E.g.: void stars () // declarator
{
for(int j=10; j>=0; j--) //function body
cout<<”*”; cout< What is the difference between an ARRAY and a LIST?

Answer1
Array is collection of homogeneous elements.
List is collection of heterogeneous elements.

For Array memory allocated is static and continuous.
For List memory allocated is dynamic and Random.

Array: User need not have to keep in track of next memory allocation.
List: User has to keep in Track of next location where memory is allocated.

Answer2
Array uses direct access of stored members, list uses sequencial access for members.

//With Array you have direct access to memory position 5
Object x = a[5]; // x takes directly a reference to 5th element of array

//With the list you have to cross all previous nodes in order to get the 5th node:
list mylist;
list::iterator it;

for( it = list.begin() ; it != list.end() ; it++ )
{
if( i==5)
{
x = *it;
break;
}
i++;
}

What is a template?

Templates allow to create generic functions that admit any data type as parameters and return value without having to overload the function with all the possible data types. Until certain point they fulfill the functionality of a macro. Its prototype is any of the two following ones:

template function_declaration; template function_declaration;

The only difference between both prototypes is the use of keyword class or typename, its use is indistinct since both expressions have exactly the same meaning and behave exactly the same way.

You have two pairs: new() and delete() and another pair : alloc() and free(). Explain differences between eg. new() and malloc()

Answer1
1.) “new and delete” are preprocessors while “malloc() and free()” are functions. [we dont use brackets will calling new or delete].
2.) no need of allocate the memory while using “new” but in “malloc()” we have to use “sizeof()”.
3.) “new” will initlize the new memory to 0 but “malloc()” gives random value in the new alloted memory location [better to use calloc()]

Answer2
new() allocates continous space for the object instace
malloc() allocates distributed space.
new() is castless, meaning that allocates memory for this specific type,
malloc(), calloc() allocate space for void * that is cated to the specific class type pointer.

What is the difference between class and structure?

Structure: Initially (in C) a structure was used to bundle different type of data types together to perform a particular functionality. But C++ extended the structure to contain functions also. The major difference is that all declarations inside a structure are by default public.
Class: Class is a successor of Structure. By default all the members inside the class are private.

What is RTTI?

Runtime type identification (RTTI) lets you find the dynamic type of an object when you have only a pointer or a reference to the base type. RTTI is the official way in standard C++ to discover the type of an object and to convert the type of a pointer or reference (that is, dynamic typing). The need came from practical experience with C++. RTTI replaces many homegrown versions with a solid, consistent approach.

What is encapsulation?

Packaging an object’s variables within its methods is called encapsulation.

Explain term POLIMORPHISM and give an example using eg. SHAPE object: If I have a base class SHAPE, how would I define DRAW methods for two objects CIRCLE and SQUARE

Answer1
POLYMORPHISM : A phenomenon which enables an object to react differently to the same function call.
in C++ it is attained by using a keyword virtual

Example
public class SHAPE
{
public virtual void SHAPE::DRAW()=0;
}
Note here the function DRAW() is pure virtual which means the sub classes must implement the DRAW() method and SHAPE cannot be instatiated

public class CIRCLE::public SHAPE
{
public void CIRCLE::DRAW()
{
// TODO drawing circle
}
}
public class SQUARE::public SHAPE
{
public void SQUARE::DRAW()
{
// TODO drawing square
}
}
now from the user class the calls would be like
globally
SHAPE *newShape;

When user action is to draw
public void MENU::OnClickDrawCircle(){
newShape = new CIRCLE();
}

public void MENU::OnClickDrawCircle(){
newShape = new SQUARE();
}

the when user actually draws
public void CANVAS::OnMouseOperations(){
newShape->DRAW();
}

Answer2
class SHAPE{
public virtual Draw() = 0; //abstract class with a pure virtual method
};

class CIRCLE{
public int r;
public virtual Draw() { this->drawCircle(0,0,r); }
};

class SQURE
public int a;
public virtual Draw() { this->drawRectangular(0,0,a,a); }
};

Each object is driven down from SHAPE implementing Draw() function in its own way.

What is an object?

Object is a software bundle of variables and related methods. Objects have state and behavior.

How can you tell what shell you are running on UNIX system?

You can do the Echo $RANDOM. It will return a undefined variable if you are from the C-Shell, just a return prompt if you are from the Bourne shell, and a 5 digit random numbers if you are from the Korn shell. You could also do a ps -l and look for the shell with the highest PID.

Describe PRIVATE, PROTECTED and PUBLIC – the differences and give examples.

class Point2D{
int x; int y;
public int color;
protected bool pinned;
public Point2D() : x(0) , y(0) {} //default (no argument) constructor
};
Point2D MyPoint;
You cannot directly access private data members when they are declared (implicitly) private:
MyPoint.x = 5; // Compiler will issue a compile ERROR
//Nor yoy can see them:
int x_dim = MyPoint.x; // Compiler will issue a compile ERROR
On the other hand, you can assign and read the public data members:
MyPoint.color = 255; // no problem
int col = MyPoint.color; // no problem
With protected data members you can read them but not write them: MyPoint.pinned = true; // Compiler will issue a compile ERROR
bool isPinned = MyPoint.pinned; // no problem

What is namespace?

Namespaces allow us to group a set of global classes, objects and/or functions under a name. To say it somehow, they serve to split the global scope in sub-scopes known as namespaces.
The form to use namespaces is:
namespace identifier { namespace-body }
Where identifier is any valid identifier and namespace-body is the set of classes, objects and functions that are included within the namespace. For example:
namespace general { int a, b; } In this case, a and b are normal variables integrated within the general namespace. In order to access to these variables from outside the namespace we have to use the scope operator ::. For example, to access the previous variables we would have to put:
general::a general::b
The functionality of namespaces is specially useful in case that there is a possibility that a global object or function can have the same name than another one, causing a redefinition error.

What do you mean by inheritance?

Inheritance is the process of creating new classes, called derived classes, from existing classes or base classes. The derived class inherits all the capabilities of the base class, but can add embellishments and refinements of its own.

What is a COPY CONSTRUCTOR and when is it called?

A copy constructor is a method that accepts an object of the same class and copies it’s data members to the object on the left part of assignement:
class Point2D{
int x; int y;
public int color;
protected bool pinned;
public Point2D() : x(0) , y(0) {} //default (no argument) constructor
public Point2D( const Point2D & ) ;
};
Point2D::Point2D( const Point2D & p )
{
this->x = p.x;
this->y = p.y;
this->color = p.color;
this->pinned = p.pinned;
}
main(){
Point2D MyPoint;
MyPoint.color = 345;
Point2D AnotherPoint = Point2D( MyPoint ); // now AnotherPoint has color = 345

What is Boyce Codd Normal form?

A relation schema R is in BCNF with respect to a set F of functional dependencies if for all functional dependencies in F+ of the form a-> , where a and b is a subset of R, at least one of the following holds:
* a- > b is a trivial functional dependency (b is a subset of a)
* a is a superkey for schema R

What is virtual class and friend class?

Friend classes are used when two or more classes are designed to work together and need access to each other's implementation in ways that the rest of the world shouldn't be allowed to have. In other words, they help keep private things private. For instance, it may be desirable for class DatabaseCursor to have more privilege to the internals of class Database than main() has.

What is the word you will use when defining a function in base class to allow this function to be a polimorphic function?

virtual

What do you mean by binding of data and functions?

Encapsulation.

What are 2 ways of exporting a function from a DLL?

1.Taking a reference to the function from the DLL instance.
2. Using the DLL ’s Type Library.

Important C Questions With answers

Declarations and Initializations
Variables and Data types
Expressions
Arrays and Pointers
Functions
Structures, Unions, and Enumerations
Preprocessors ( Macros,Headers etc. )
Bit Fiddling
File Operations
Compiling and Linking
Linked Lists
Trees
Sorting
Frequently Asked Programs

Monday, May 28, 2007

C/C++ Faqs Collection 1

C++ on Unix


  1. What is a Make file?(Fujitsu) Make file is a utility in Unix to help compile large programs. It helps by only compiling the portion of the program that has been changed.
  2. What is deadlock? (Novell) Deadlock is a situation when two or more processes prevent each other from running.Example: if T1 is holding x and waiting for y to be free and T2 holding y and waiting for x to be free deadlock happens.
  3. What is semaphore? (Novell) Semaphore is a special variable, it has two methods: up and down. Semaphore performs atomic operations, which means ones a semaphore is called it can not be inturrupted.
  4. Is C an object-oriented language? (Microsoft) C is not an object-oriented language, but limited object-oriented programming can be done in C.
  5. Name some major differences between C++ and Java. C++ has pointers; Java does not. Java is platform-independent; C++ is not. Java has garbage collection; C++ does no

Advanced C++ and STL Questions

: How do you link a C++ program to C functions?
A: By using the extern "C" linkage specification around the C function declarations.

Q: Explain the scope resolution operator.
A: It permits a program to reference an identifier in the global scope that has been hidden by another identifier with the same name in the local scope.

Q: What are the differences between a C++ struct and C++ class?
A: The default member and base-class access specifiers are different.

Q: How many ways are there to initialize an int with a constant?
A: Two.

There are two formats for initializers in C++ as shown in the example that follows. The first format uses the traditional C notation. The second format uses constructor notation.

int foo = 123;

int bar (123);

Q: How does throwing and catching exceptions differ from using setjmp and longjmp?
A: The throw operation calls the destructors for automatic objects instantiated since entry to the try block.

Q: What is your reaction to this line of code?
delete this;
A: It’s not a good practice.

Q: What is a default constructor?
A: A constructor that has no arguments.

Q: What is a conversion constructor?
A: A constructor that accepts one argument of a different type.

Q: What is the difference between a copy constructor and an overloaded assignment operator?
A: A copy constructor constructs a new object by using the content of the argument object. An overloaded assignment operator assigns the contents of an existing object to another existing object of the same class.

Q: When should you use multiple inheritance?
A: There are three acceptable answers: "Never," "Rarely," and "When the problem domain cannot be accurately modeled any other way."

Q: What is a virtual destructor?
A: The simple answer is that a virtual destructor is one that is declared with the virtual attribute.

Q: Explain the ISA and HASA class relationships. How would you implement each in a class design?
A: A specialized class "is" a specialization of another class and, therefore, has the ISA relationship with the other class. An Employee ISA Person. This relationship is best implemented with inheritance. Employee is derived from Person. A class may have an instance of another class. For example, an employee "has" a salary, therefore the Employee class has the HASA relationship with the Salary class. This relationship is best implemented by embedding an object of the Salary class in the Employee class.

Q: When is a template a better solution than a base class?
A: When you are designing a generic class to contain or otherwise manage objects of other types, when the format and behavior of those other types are unimportant to their containment or management, and particularly when those other types are unknown (thus, the genericity) to the designer of the container or manager class.

Q: What is a mutable member?
A: One that can be modified by the class even when the object of the class or the member function doing the modification is const.

Q: What is an explicit constructor?
A: A conversion constructor declared with the explicit keyword. The compiler does not use an explicit constructor to implement an implied conversion of types. It’s purpose is reserved explicitly for construction.

Q: What is the Standard Template Library?
A: A library of container templates approved by the ANSI committee for inclusion in the standard C++ specification.
A programmer who then launches into a discussion of the generic programming model, iterators, allocators, algorithms, and such, has a higher than average understanding of the new technology that STL brings to C++ programming.

Q: Describe run-time type identification.
A: The ability to determine at run time the type of an object by using the typeid operator or the dynamic_cast operator.

Q: What problem does the namespace feature solve?
A: Multiple providers of libraries might use common global identifiers causing a name collision when an application tries to link with two or more such libraries. The namespace feature surrounds a library’s external declarations with a unique namespace that eliminates the potential for those collisions.
This solution assumes that two library vendors don’t use the same namespace identifier, of course.

Q: Are there any new intrinsic (built-in) data types?
A: Yes. The ANSI committee added the bool intrinsic type and its true and false value keywords.



C++ Coding Interview Questions

Design and implement a String class that satisfies the following:
  • Supports embedded nulls
  • Provide the following methods (at least)
    • Constructor
    • Destructor
    • Copy constructor
    • Assignment operator
    • Addition operator (concatenation)
    • Return character at location
    • Return substring at location
    • Find substring
  • Provide versions of methods for String and for char* arguments

2. Given the following classes

class Fruit {
// …
}

class Apple : public Fruit {
// …
}

class Peach : public Fruit {
// …
}

// Container of fruit
class BasketOfFruit {
BasketOfFruit() ;
void insert( Fruit & f ) ;
// …
}

// Container of apples
class BasketOfApples /* ??? */ {
// …
}

Should BasketOfApples derive from BasketOfFruit? Why or why not?
What is the general principle that determines the answer?

3. Describe briefly what the following function does. What standard function is it most like ?

int f( char *p ) {
int n = 0 ;
while ( *p != 0 ) n = 10*n + *p++ - ‘0′ ;
return n ;
}

4. Describe briefly what function ‘a’ does in the following code fragment.

struct s {
struct s *next ;
}

a( struct s *p, struct s *x ) {
while ( p->next != 0 ) p = p->next ;
p->next = x ;
x->next = 0 ;
}

5. What default methods are declared implicitly by the C++ compiler for the class below:

class Empty
{
};

6. Given a system with a hard realtime priority, multithreaded architecture, with priorities from 1 (least) to 5 (most), explain the major flaw in the design below:

The following objects are shared between the threads:

Disk : This class is a singleton. The read() and write() methods both block on a simple atomic lock()/unlock() shared between the two. (ie, only one thread can access the disk, thru either read or write, at any given time). It also has a waitForData() method, which blocks (without claiming the lock) until either a timeout elapses, or data is ready. It returns true upon returning due to new data, false upon returning due to the timeout.

Network : This class is a singleton. The read() and write() methods both block on a simple atomic lock()/unlock() shared between the two. (ie, only one thread can access the disk, thru either read or write, at any given time).

Sensor: The Sensor class accesses a number of physical sensors. The first method, ‘waitForData()’, blocks until data has been collected from the sensors. The second method, ‘processData()’, does a series of long and cpu-intensive calculations on the data. These calculations often take several minutes. It then returns the processed data.

Each of the following threads is running concurrently. Assume that the psuedocode in each thread is looped infinitely (ie, encased in a while(true) { }. It is extremely important that information buffered to the disk be sent to the network as quickly as possible, this is why Thread 1 runs at priority 5. The system conditions checked in thread 3 are not particularly important events (not as important as the calculations done in thread 2). If the events aren’t transmitted over the network for several minutes, it’s not a problem at all. They do, however, contain a large amount of system information. Thread 4 watches for serious system alarms, indicating serious problems. These are a serious concern and if not quickly buffered to the disk and sent to the network, can cause serious revenue loss.

Thread 1: (priority: 5)
while(!Disk.waitForData()) { yield(); } /* Wait until someone has
written data to the disk */
Network.write(Disk.read()); /* Write the data buffered on the disk to
the network */

Thread 2: (priority: 2)
while(!Sensor.waitForData()) { yield(); } /* Wait until the sensors
have picked up data */
Disk.write(Sensor.processData()); /* process the data and write it to
the disk. */

Thread 3: (priority: 1)

if (checkSystemCondition1()) /* If system condition 1 is true.. */
Disk.write(SystemCond1Data); /* Grab the data on the system
condition and buffer it to disk */
if (checkSystemCondition2()) /* see above*/
Disk.write(SystemCond2Data);
if (checkSystemCondition3()) /* see above */
Disk.write(SystemCond3Data);
yield();

Thread 4: (priority: 4)
if (checkAlarms()) /* If any serious alarms exist */
Disk.write(AlarmData); /* Buffer that data to disk for immediate
network transmit */
yield();

Basic C++ Interview Questions

Question: Suppose that data is an array of 1000 integers. Write a single function call that will sort the 100 elements data [222] through data [321].
Answer: quicksort ((data + 222), 100);

2.Question: Which recursive sorting technique always makes recursive calls to sort subarrays that are about half size of the original array?
Answer: Mergesort always makes recursive calls to sort subarrays that are about half size of the original array, resulting in O(n log n) time.

3.Question: What is the difference between an external iterator and an internal iterator? Describe an advantage of an external iterator.
Answer: .An internal iterator is implemented with member functions of the class that has items to step through. .An external iterator is implemented as a separate class that can be "attach" to the object that has items to step through. .An external iterator has the advantage that many difference iterators can be active simultaneously on the same object.

4.Question: Why are arrays usually processed with for loop?
Answer: The real power of arrays comes from their facility of using an index variable to traverse the array, accessing each element with the same expression a[i]. All the is needed to make this work is a iterated statement in which the variable i serves as a counter, incrementing from 0 to a.length -1. That is exactly what a loop does.

5.Question: What is an HTML tag?
Answer: An HTML tag is a syntactical construct in the HTML language that abbreviates specific instructions to be executed when the HTML script is loaded into a Web browser. It is like a method in Java, a function in C++, a procedure in Pascal, or a subroutine in FORTRAN.


Algorithm Specific C++ Interview Questions


Q1 What are the advantages and disadvantages of B-star trees over Binary trees? (Asked by Motorola people)

A1 B-star trees have better data structure and are faster in search than Binary trees, but it’s harder to write codes for B-start trees.

Q2 Write the psuedo code for the Depth first Search.(Asked by Microsoft)

A2

dfs(G, v) //OUTLINE
Mark v as "discovered"
For each vertex w such that edge vw is in G:
If w is undiscovered:
dfs(G, w); that is, explore vw, visit w, explore from there
as much as possible, and backtrack from w to v.
Otherwise:
"Check" vw without visiting w.
Mark v as "finished".

Q3 Describe one simple rehashing policy.(Asked by Motorola people)

A3 The simplest rehashing policy is linear probing. Suppose a key K hashes to location i. Suppose other key occupies H[i]. The following function is used to generate alternative locations:

rehash(j) = (j + 1) mod h

where j is the location most recently probed. Initially j = i, the hash code for K. Notice that this version of rehash does not depend on K.

Q4 Describe Stacks and name a couple of places where stacks are useful. (Asked by Microsoft)

A4 A Stack is a linear structure in which insertions and deletions are always made at one end, called the top. This updating policy is called last in, first out (LIFO). It is useful when we need to check some syntex errors, such as missing parentheses.

Q5 Suppose a 3-bit sequence number is used in the selective-reject ARQ, what is the maximum number of frames that could be transmitted at a time? (Asked by Cisco)

A5 If a 3-bit sequence number is used, then it could distinguish 8 different frames. Since the number of frames that could be transmitted at a time is no greater half the numner of frames that could be distinguished by the sequence number, so at most 4 frames can be transmitted at a time.

C++ Networking Question


Q: What is the difference between Stack and Queue?

A: Stack is a Last In First Out (LIFO) data structure.

Queue is a First In First Out (FIFO) data structure

Q: Write a fucntion that will reverse a string. (Microsoft)

A: char *strrev(char *s)

{

int i = 0, len = strlen(s);

char *str;

if ((str = (char *)malloc(len+1)) == NULL) /*cannot allocate memory */

err_num = 2;

return (str);

}

while(len)

str[i++]=s[–len];

str[i] = NULL;

return (str);

}

Q: What is the software Life-Cycle?

A: The software Life-Cycle are

1) Analysis and specification of the task

2) Design of the algorithms and data structures

3) Implementation (coding)

4) Testing

5) Maintenance and evolution of the system

6) Obsolescence

Q: What is the difference between a Java application and a Java applet?

A: The difference between a Java application and a Java applet is that a

Java application is a program that can be executed using the Java

interpeter, and a JAVA applet can be transfered to different networks

and executed by using a web browser (transferable to the WWW).

Q: Name 7 layers of the OSI Reference Model? (from Cisco)

A: -Application layer

-Presentation layer

-Session layer

-Transport layer

-Network layer

-Data Link layer

-Physical layer


C++ OOP Interview Questions



1. How do you write a function that can reverse a linked-list? (Cisco System)

void reverselist(void)
{
if(head==0)
return;
if(head->next==0)
return;
if(head->next==tail)
{
head->next = 0;
tail->next = head;
}
else
{
node* pre = head;
node* cur = head->next;
node* curnext = cur->next;
head->next = 0;
cur->next = head;
  for(; curnext!=0; )
{
cur->next = pre;
pre = cur;
cur = curnext;
curnext = curnext->next;
}
  curnext->next = cur;
}
}

2. What is polymorphism?

Polymorphism is the idea that a base class can be inherited by several classes. A base class pointer can point to its child class and a base class array can store different child class objects.

3. How do you find out if a linked-list has an end? (i.e. the list is not a cycle)

You can find out by using 2 pointers. One of them goes 2 nodes each time. The second one goes at 1 nodes each time. If there is a cycle, the one that goes 2 nodes each time will eventually meet the one that goes slower. If that is the case, then you will know the linked-list is a cycle.

4. How can you tell what shell you are running on UNIX system?

You can do the Echo $RANDOM. It will return a undefined variable if you are from the C-Shell, just a return prompt if you are from the Bourne shell, and a 5 digit random numbers if you are from the Korn shell. You could also do a ps -l and look for the shell with the highest PID.

5. What is Boyce Codd Normal form?

A relation schema R is in BCNF with respect to a set F of functional dependencies if for all functional dependencies in F+ of the form a->b, where a and b is a subset of R, at least one of the following holds:

  • a->b is a trivial functional dependency (b is a subset of a)
  • a is a superkey for schema R

C++ Job Interview Questions

From Microsoft) Assume I have a linked list contains all of the alphabets from ‘A’ to ‘Z’. I want to find the letter ‘Q’ in the list, how does you perform the search to find the ‘Q’?Answer: In a linked list, we only know about the header and other elements are invisible unless we go through the node one by one. Since we have go through every single node to find ‘Q’, the search time for a linked list is linear which is O (N).

From IBM) How do you think about your school?
: I enjoy studying in our school because we have many professors and instructors are from local companies. Their professions lead us more close to local industries.

(From IBM) What classes you have enjoyed the most during your school years?
Answer: I like the class I am taking this semester, which involves a group project that needs great amount of team efforts. I really enjoy work with a group of people because we can learn new materials mutually.

>

m IBM) According to your group project you just mentioned, what’s the responsibility for each member in your group?
Answer: We have five people in our group. So far we have two web servers set up; one will be the back up system and the other will be the main system. Our leader coordinates the schedule. Two members are working on the database and do the coding for the connection between database and Java serverlets. One member is working on the user browser interface. All members will assign some classes to work on and perform the final test at the end. We have group meeting every Saturday to ensure our schedule is on track.

Can you work under pressure?
Answer: I worked for Sega of America in the hardware development group three years ago. They were working on the next generation of gaming machine (which is the “Dreamcast” we seen today in the market). My duty was to ensure the quality of prototypes that just built from manufacture were ready for engineers to test. I managed to balance the schedules and pressures from school and work.


C++ Object Oriented Interviews Questions


What is pure virtual function?
A class is made abstract by declaring one or more of its virtual functions to be pure. A pure virtual function is one with an initializer of = 0 in its declaration

Q. Write a Struct Time where integer m, h, s are its members
struct Time
{
int m;
int h;
int s;
};

ow do you traverse a Btree in Backward in-order?
Process the node in the right subtree
Process the root
Process the node in the left subtree

Q. What is the two main roles of Operating System?
As a resource manager
As a virtual machine

Q. In the derived class, which data member of the base class are visible?
In the public and protected sections.


C++ Interviews Question


  1. In C++, what is the difference between method overloading and method overriding?Overloading a method (or function) in C++ is the ability for functions of the same name to be defined as long as these methods have different signatures (different set of parameters). Method overriding is the ability of the inherited class rewriting the virtual method of the base class.
  2. What methods can be overridden in Java? In C++ terminology, all public methods in Java are virtual. Therefore, all Java methods can be overwritten in subclasses except those that are declared final, static, and private.
  3. In C, what is the difference between a static variable and global variable? A static variable declared outside of any function is accessible only to all the functions defined in the same file (as the static variable). However, a global variable can be accessed by any function (including the ones from different files).
  4. In C, why is the void pointer useful? When would you use it? The void pointer is useful becuase it is a generic pointer that any pointer can be cast into and back again without loss of information.
  5. What are the defining traits of an object-oriented language? The defining traits of an object-oriented langauge are:
    • encapsulation
    • inheritance
    • polymorphism

C++ Code Examples


Q: Write a short code using C++ to print out all odd number from 1 to 100 using a for loop(Asked by Intacct.com people)

for( unsigned int i = 1; i < = 100; i++ )    if( i & 0x00000001 )        cout <<> 

ISO layers and what layer is the IP operated from?( Asked by Cisco system people)

cation, Presentation, Session, Transport, Network, Data link and Physical. The IP is operated in the Network layer.

3.Q: Write a program that ask for user input from 5 to 9 then calculate the average( Asked by Cisco system people)

A.int main()
{
int MAX=4;
int total =0;
int average=0;
int numb;
cout<<"Please enter your input from 5 to 9"; cin>>numb;
if((numb <5)&&(numb>9))
cout<<"please re type your input"; else for(i=0;i<=MAX; i++) { total = total + numb; average= total /MAX; } cout<<"The average number is"<<

return 0;
}

4.Q: Can you be bale to identify between Straight- through and Cross- over cable wiring? and in what case do you use Straight- through and Cross-over? (Asked by Cisco system people)

A. Straight-through is type of wiring that is one to to one connection Cross- over is type of wiring which those wires are got switched

We use Straight-through cable when we connect between NIC Adapter and Hub. Using Cross-over cable when connect between two NIC Adapters or sometime between two hubs.

5.Q: If you hear the CPU fan is running and the monitor power is still on, but you did not see any thing show up in the monitor screen. What would you do to find out what is going wrong? (Asked by WNI people)

A. I would use the ping command to check whether the machine is still alive(connect to the network) or it is dead.

C interview question

1. What will print out?

main()
{
char *p1=“name”;
char *p2;
p2=(char*)malloc(20);
memset (p2, 0, 20);
while(*p2++ = *p1++);
printf(“%s\n”,p2);

}

Answer:empty string.
2. What will be printed as the result of the operation below:

main()
{
int x=20,y=35;
x=y++ + x++;
y= ++y + ++x;
printf(“%d%d\n”,x,y);

}

Answer : 5794
3. What will be printed as the result of the operation below:

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

}

Answer: 5,20,1
4. What will be printed as the result of the operation below:

#define swap(a,b) a=a+b;b=a-b;a=a-b;

void main()
{
int x=5, y=10;
swap (x,y);
printf(“%d %d\n”,x,y);
swap2(x,y);
printf(“%d %d\n”,x,y);
}

int swap2(int a, int b)
{
int temp;
temp=a;
b=a;
a=temp;
return 0;

}

Answer: 10, 5
10, 5
5. What will be printed as the result of the operation below:

main()
{
char *ptr = ” Cisco Systems”;
*ptr++; printf(“%s\n”,ptr);
ptr++;
printf(“%s\n”,ptr);

}

Answer:Cisco Systems
isco systems
6. What will be printed as the result of the operation below:

main()
{
char s1[]=“Cisco”;
char s2[]= “systems”;
printf(“%s”,s1);
}

Answer: Cisco
7. What will be printed as the result of the operation below:

main()
{
char *p1;
char *p2;

p1=(char *)malloc(25);
p2=(char *)malloc(25);

strcpy(p1,”Cisco”);
strcpy(p2,“systems”);
strcat(p1,p2);

printf(“%s”,p1);

}

Answer: Ciscosystems
8. The following variable is available in file1.c, who can access it?:

static int average;

Answer: all the functions in the file1.c can access the variable.
9. WHat will be the result of the following code?

#define TRUE 0 // some code

while(TRUE)
{

// some code

}

Answer: This will not go into the loop as TRUE is defined as 0.
10. What will be printed as the result of the operation below:

int x;
int modifyvalue()
{
return(x+=10);
}

int changevalue(int x)
{
return(x+=1);
}

void main()
{
int x=10;
x++;
changevalue(x);
x++;
modifyvalue();
printf("First output:%d\n",x);

x++;
changevalue(x);
printf("Second output:%d\n",x);
modifyvalue();
printf("Third output:%d\n",x);

}

Answer: 12 , 13 , 13
11. What will be printed as the result of the operation below:

main()
{
int x=10, y=15;
x = x++;
y = ++y;
printf(“%d %d\n”,x,y);

}

Answer: 11, 16
12. What will be printed as the result of the operation below:

main()
{
int a=0;
if(a==0)
printf(“Cisco Systems\n”);
printf(“Cisco Systems\n”);

}

Answer: Two lines with “Cisco Systems” will be printed.

Good C interview Questions



  1. How do you decide which integer type to use?
  2. What should the 64-bit integer type on new, 64-bit machines be?
  3. What’s the best way to declare and define global variables?
  4. What does extern mean in a function declaration?
  5. What’s the auto keyword good for?
  6. I can’t seem to define a linked list node which contains a pointer to itself.
  7. How do I declare an array of N pointers to functions returning pointers to functions returning pointers to characters?
  8. How can I declare a function that returns a pointer to a function of its own type?
  9. My compiler is complaining about an invalid redeclaration of a function, but I only define it once and call it once. What’s happening?
  10. What can I safely assume about the initial values of variables which are not explicitly initialized?
  11. Why can’t I initialize a local array with a string?
  12. What is the difference between char a[] = “string”; and char *p = “string”; ?
  13. How do I initialize a pointer to a function?

C interview questions



  1. What does static variable mean?
  2. What is a pointer?
  3. What is a structure?
  4. What are the differences between structures and arrays?
  5. In header files whether functions are declared or defined?
  6. What are the differences between malloc() and calloc()?
  7. What are macros? What are the advantages and disadvantages?
  8. Difference between pass by reference and pass by value?
  9. What is static identifier?
  10. Where are the auto variables stored?
  11. Where does global, static, local, register variables, free memory and C Program instructions get stored?
  12. Difference between arrays and linked list?
  13. What are enumerations?
  14. Describe about storage allocation and scope of global, extern, static, local and register variables?
  15. What are register variables? What are the advantage of using register variables?
  16. What is the use of typedef?
  17. Can we specify variable field width in a scanf() format string? If possible how?
  18. Out of fgets() and gets() which function is safe to use and why?
  19. Difference between strdup and strcpy?
  20. What is recursion?
  21. Differentiate between a for loop and a while loop? What are it uses?
  22. What are the different storage classes in C?
  23. Write down the equivalent pointer expression for referring the same element a[i][j][k][l]?
  24. What is difference between Structure and Unions?
  25. What the advantages of using Unions?
  26. What are the advantages of using pointers in a program?
  27. What is the difference between Strings and Arrays?
  28. In a header file whether functions are declared or defined?
  29. What is a far pointer? where we use it?
  30. How will you declare an array of three function pointers where each function receives two ints and returns a float?
  31. What is a NULL Pointer? Whether it is same as an uninitialized pointer?
  32. What is a NULL Macro? What is the difference between a NULL Pointer and a NULL Macro?
  33. What does the error ‘Null Pointer Assignment’ mean and what causes this error?
  34. What is near, far and huge pointers? How many bytes are occupied by them?
  35. How would you obtain segment and offset addresses from a far address of a memory location?
  36. Are the expressions arr and *arr same for an array of integers?
  37. Does mentioning the array name gives the base address in all the contexts?
  38. Explain one method to process an entire string as one unit?
  39. What is the similarity between a Structure, Union and enumeration?
  40. Can a Structure contain a Pointer to itself?
  41. How can we check whether the contents of two structure variables are same or not?
  42. How are Structure passing and returning implemented by the complier?
  43. How can we read/write Structures from/to data files?
  44. What is the difference between an enumeration and a set of pre-processor # defines?
  45. What do the ‘c’ and ‘v’ in argc and argv stand for?
  46. Are the variables argc and argv are local to main?
  47. What is the maximum combined length of command line arguments including the space between adjacent arguments?
  48. If we want that any wildcard characters in the command line arguments should be appropriately expanded, are we required to make any special provision? If yes, which?
  49. Does there exist any way to make the command line arguments available to other functions without passing them as arguments to the function?
  50. What are bit fields? What is the use of bit fields in a Structure declaration?
  51. To which numbering system can the binary number 1101100100111100 be easily converted to?
  52. Which bit wise operator is suitable for checking whether a particular bit is on or off?
  53. Which bit wise operator is suitable for turning off a particular bit in a number?
  54. Which bit wise operator is suitable for putting on a particular bit in a number?
  55. Which bit wise operator is suitable for checking whether a particular bit is on or off?
  56. Which one is equivalent to multiplying by 2?
    • Left shifting a number by 1
    • Left shifting an unsigned int or char by 1?
  57. Write a program to compare two strings without using the strcmp() function.
  58. Write a program to concatenate two strings.
  59. Write a program to interchange 2 variables without using the third one.
  60. Write programs for String Reversal. The same for Palindrome check.
  61. Write a program to find the Factorial of a number.
  62. Write a program to generate the Fibonacci Series?
  63. Write a program which employs Recursion?
  64. Write a program which uses command line arguments.
  65. Write a program which uses functions like strcmp(), strcpy(), etc.
  66. What are the advantages of using typedef in a program?
  67. How would you dynamically allocate a one-dimensional and two-dimensional array of integers?
  68. How can you increase the size of a dynamically allocated array?
  69. How can you increase the size of a statically allocated array?
  70. When reallocating memory if any other pointers point into the same piece of memory do you have to readjust these other pointers or do they get readjusted automatically?
  71. Which function should be used to free the memory allocated by calloc()?
  72. How much maximum can you allocate in a single call to malloc()?
  73. Can you dynamically allocate arrays in expanded memory?
  74. What is object file? How can you access object file?
  75. Which header file should you include if you are to develop a function which can accept variable number of arguments?
  76. Can you write a function similar to printf()?
  77. How can a called function determine the number of arguments that have been passed to it?
  78. Can there be at least some solution to determine the number of arguments passed to a variable argument list function?
  79. How do you declare the following:
    • An array of three pointers to chars
    • An array of three char pointers
    • A pointer to array of three chars
    • A pointer to function which receives an int pointer and returns a float pointer
    • A pointer to a function which receives nothing and returns nothing
  80. What do the functions atoi(), itoa() and gcvt() do?
  81. Does there exist any other function which can be used to convert an integer or a float to a string?
  82. How would you use qsort() function to sort an array of structures?
  83. How would you use qsort() function to sort the name stored in an array of pointers to string?
  84. How would you use bsearch() function to search a name stored in array of pointers to string?
  85. How would you use the functions sin(), pow(), sqrt()?
  86. How would you use the functions memcpy(), memset(), memmove()?
  87. How would you use the functions fseek(), freed(), fwrite() and ftell()?
  88. How would you obtain the current time and difference between two times?
  89. How would you use the functions randomize() and random()?
  90. How would you implement a substr() function that extracts a sub string from a given string?
  91. What is the difference between the functions rand(), random(), srand() and randomize()?
  92. What is the difference between the functions memmove() and memcpy()?
  93. How do you print a string on the printer?
  94. Can you use the function fprintf() to display the output on the screen?
  95. What is a linklist and why do we use it when we have arrays? - I feel the correct answer should be linklist is used in cases where you don’t know the memory required to store a data structure and need to allocate is dynamically on demand.
  96. How do you detect a loop in linked list?
  97. What is the difference between main() in C and main() in C++?
  98. what will be printed out when the following code is executed:

    main()
    {
    printf("%x",-1<<4);>

  99. Programming Interviews Questions


  100. How can you defined OOP?
  101. How can you use OOP in your projects/products/applications?
  102. What is copy constructor?
  103. How many types of copy constructor are there?
  104. What shallow copy constructor does/behaves?
  105. Does C++ support copy constructor?
  106. Does Java support copy constructor?
  107. (If the answer to the previous question was correct) Why doesn’t Java support copy constructor?
  108. What is software life cycle?

C++ Object Interviews Questions



  1. What is a modifier? 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’. Example: The function mod is a modifier in the
    following code snippet:
    class test
    {
    int x,y;
    public:
    test()
    {
    x=0; y=0;
    }
    void mod()
    {
    x=10;
    y=15;
    }
    };
  2. What is an accessor? An accessor is a class operation that
    does not modify the state of an object. The accessor functions need to
    be declared as const operations
  3. Differentiate between a template class and class template.
    Template class: A generic definition or a parameterized class not
    instantiated until the client provides the needed information. It’s
    jargon for plain templates. Class template: A class template specifies
    how individual classes can be constructed much like the way a class
    specifies how individual objects can be constructed. It’s jargon for
    plain classes.
  4. When does a name clash occur? A name clash occurs
    when a name is defined in more than one place. For example., two
    different class libraries could give two different classes the same
    name. If you try to use many class libraries at the same time, there is
    a fair chance that you will be unable to compile or link the program
    because of name clashes.
  5. Define namespace. It is a feature in C++ to
    minimize name collisions in the global name space. This namespace
    keyword assigns a distinct name to a library that allows other
    libraries to use the same identifier names without creating any name
    collisions. Furthermore, the compiler uses the namespace signature for
    differentiating the definitions.
  6. What is the use of ‘using’ declaration.
    A using declaration makes it possible to use a name from a namespace without the scope operator.
  7. 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.
  8. List out some of the OODBMS available. GEMSTONE/OPAL
    of Gemstone systems, ONTOS of Ontos, Objectivity of Objectivity Inc,
    Versant of Versant object technology, Object store of Object Design,
    ARDENT of ARDENT software, POET of POET software.
  9. List out some of the object-oriented methodologies. Object Oriented Development (OOD) (Booch 1991,1994), Object
    Oriented Analysis and Design (OOA/D) (Coad and Yourdon 1991), Object
    Modelling Techniques (OMT) (Rumbaugh 1991), Object Oriented Software
    Engineering (Objectory) (Jacobson 1992), Object Oriented Analysis (OOA)
    (Shlaer and Mellor 1992), The Fusion Method (Coleman 1991).
  10. What is an incomplete type? Incomplete types
    refers to pointers in which there is non availability of the
    implementation of the referenced location or it points to some location
    whose value is not available for modification.
     int *i=0x400  // i points to address 400
    *i=0; //set the value of memory location pointed by i.

    Incomplete types are otherwise called uninitialized pointers.

  11. 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. The following
    code snippet shows this:
    class Sample
    {
    public:
    int *ptr;
    Sample(int i)
    {
    ptr = new int(i);
    }

    ~Sample()
    {
    delete ptr;
    }
    void PrintVal()
    {
    cout << "The value is " << *ptr; } }; void SomeFunc(Sample x) { cout << "Say i am in someFunc " << s1 =" 10;">

    In the above example when PrintVal() function is
    called it is called by the pointer that has been freed by the
    destructor in SomeFunc.

  12. Differentiate between the message and method.
    Message:
    • Objects communicate by sending messages to each other.
    • A message is sent to invoke a method.

    Method

    • Provides response to a message.
    • It is an implementation of an operation.
  13. What is an adaptor class or Wrapper class?
    A class that has no functionality of its own. Its member functions hide
    the use of a third party software component or an object with the
    non-compatible interface or a non-object-oriented implementation.
  14. What is a Null object? It is an object of some
    class whose purpose is to indicate that a real object of that class
    does not exist. One common use for a null object is a return value from
    a member function that is supposed to return an object with some
    specified properties but cannot find such an object.
  15. What is class invariant? A class invariant is a
    condition that defines all valid states for an object. It is a logical
    condition to ensure the correct working of a class. Class invariants
    must hold when an object is created, and they must be preserved under
    all operations of the class. In particular all class invariants are
    both preconditions and post-conditions for all operations or member
    functions of the class.
  16. What do you mean by Stack unwinding? It is a
    process during exception handling when the destructor is called for all
    local objects between the place where the exception was thrown and
    where it is caught.
  17. Define precondition and post-condition to a member function.
    Precondition: A precondition is a condition that must be true on entry
    to a member function. A class is used correctly if preconditions are
    never false. An operation is not responsible for doing anything
    sensible if its precondition fails to hold. For example, the interface
    invariants of stack class say nothing about pushing yet another element
    on a stack that is already full. We say that isful() is a precondition
    of the push operation. Post-condition: A post-condition is a condition
    that must be true on exit from a member function if the precondition
    was valid on entry to that function. A class is implemented correctly
    if post-conditions are never false. For example, after pushing an
    element on the stack, we know that isempty() must necessarily hold.
    This is a post-condition of the push operation.
  18. What are the conditions that have to be met for a condition to be an invariant of the class?
    • The condition should hold at the end of every constructor.
    • The condition should hold at the end of every mutator (non-const) operation.
  19. What are proxy objects? Objects that stand for other objects are called proxy objects or surrogates.
    template 
    class Array2D
    {
    public:
    class Array1D
    {
    public:
    T& operator[] (int index);
    const T& operator[] (int index)const;
    };

    Array1D operator[] (int index);
    const Array1D operator[] (int index) const;
    };

    The following then becomes legal:

    Array2Ddata(10,20);
    cout<

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

  20. Name some pure object oriented languages. Smalltalk, Java, Eiffel, Sather.
  21. Name the operators that cannot be overloaded. sizeof, ., .*, .->, ::, ?: Salam in the comments notes that -> can be overloaded.
  22. What is a node class? A node class is a class that,
    • relies on the base class for services and implementation,
    • provides a wider interface to the users than its base class,
    • relies primarily on virtual functions in its public interface
    • depends on all its direct and indirect base class
    • can be understood only in the context of the base class
    • can be used as base for further derivation
    • can be used to create objects.

    A node class is a class that has added new services or functionality beyond the services inherited from its base class.

  23. What is an orthogonal base class?
    If two base classes have no overlapping methods or data they are said
    to be independent of, or orthogonal to each other. Orthogonal in the
    sense means that two classes operate in different dimensions and do not
    interfere with each other in any way. The same derived class may
    inherit such classes with no difficulty.
  24. What is a container class? What are the types of container classes?

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


Interview questions on C/C++



Q1: Tell how to check whether a linked list is circular.

A: Create two pointers, each set to the start of the list. Update each as follows:

while (pointer1) {
pointer1 = pointer1->next;
pointer2 = pointer2->next; if (pointer2) pointer2=pointer2->next;
if (pointer1 == pointer2) {
print ("circularn");
}
}


Q2: OK, why does this work?

If a list is circular, at some point pointer2 will wrap around and be either at the item just before pointer1, or the item before that. Either way, it’s either 1 or 2 jumps until they meet.

How can you quickly find the number of elements stored in a a) static array b) dynamic array ?

Why is it difficult to store linked list in an array?

How can you find the nodes with repetetive data in a linked list?

Write a prog to accept a given string in any order and flash error if any of the character is different. For example : If abc is the input then abc, bca, cba, cab bac are acceptable but aac or bcd are unacceptable.

This is a C question that I had for an intern position at Microsoft: Write out a function that prints out all the permutations of a string. For example, abc would give you abc, acb, bac, bca, cab, cba. You can assume that all the characters will be unique. After I wrote out my function, he asked me to figure out from the code how many times the printf statement is run, and also questions on optimizing my algorithm.

What’s the output of the following program? Why?

#include 
main()
{
typedef union
{
int a;
char b[10];
float c;
}
Union;

Union x,y = {100};
x.a = 50;
strcpy(x.b,"hello");
x.c = 21.50;

printf("Union x : %d %s %f n",x.a,x.b,x.c );
printf("Union y :%d %s%f n",y.a,y.b,y.c);
}

Given inputs X, Y, Z and operations | and & (meaning bitwise OR and AND, respectively)

What is output equal to in

output = (X &amp;amp; Y) | (X & Z) | (Y & Z)

Windows Programming Interview Questions



  1. What are kernel objects? - - Several types of kernel objects, such as access token objects, event objects, file objects, file-mapping objects, I/O completion port objects, job objects, mailslot objects, mutex objects, pipe objects, process objects, semaphore objects, thread objects, and waitable timer objects.
  2. What is a kernel object? - Each kernel object is simply a memory block allocated by the kernel and is accessible only by the kernel. This memory block is a data structure whose members maintain information about the object. Some members (security descriptor, usage count, and so on) are the same across all object types, but most are specific to a particular object type. For example, a process object has a process ID, a base priority, and an exit code, whereas a file object has a byte offset, a sharing mode, and an open mode.
  3. User can access these kernel objects structures? - Kernel object data structures are accessible only by the kernel
  4. If we cannot alter these Kernel Object structures directly, how do our applications manipulate these kernel objects? - The answer is that Windows offers a set of functions that manipulate these structures in well-defined ways. These kernel objects are always accessible via these functions. When you call a function that creates a kernel object, the function returns a handle that identifies the object.
  5. How owns the Kernel Object? - Kernel objects are owned by the kernel, not by a process
  6. How does the kernel object outlive the process that created it? - If your process calls a function that creates a kernel object and then your process terminates, the kernel object is not necessarily destroyed. Under most circumstances, the object will be destroyed; but if another process is using the kernel object your process created, the kernel knows not to destroy the object until the other process has stopped using it
  7. Which is the data member common to all the kernel object and what is the use of it? -
  8. The usage count is one of the data members common to all kernel object types

  9. How to identify the difference between the kernel object and user object? -
  10. The easiest way to determine whether an object is a kernel object is to examine the function that creates the object. Almost all functions that create kernel objects have a parameter that allows you to specify security attribute information.

  11. What is the purpose of Process Handle Table? -
  12. When a process is initialized, the system allocates a handle table for it. This handle table is used only for kernel objects, not for User objects or GDI objects. When a process first initializes, its handle table is empty. Then when a thread in the process calls a function that creates a kernel object, such as CreateFileMapping , the kernel allocates a block of memory for the object and initializes it; the kernel then scans the process’s handle table for an empty entry

  13. Name few functions that create Kernel Objects? - HANDLE CreateThread(…),HANDLE CreateFile(..),HANDLE CreateFileMapping(..)HANDLE CreateSemaphore(..)etcAll functions that create kernel objects return process-relative handles that can be used successfully by any and all threads that are running in the same process.
  14. What is handle? - Handle value is actually the index into the process’s handle table that identifies where the kernel object’s information is stored.
  15. How the handle helps in manipulating the kernel objects? - Whenever you call a function that accepts a kernel object handle as an argument, you pass the value returned by one of the Create* functions. Internally, the function looks in your process’s handle table to get the address of the kernel object you want to manipulate and then manipulates the object’s data structure in a well-defined fashion.
  16. What happens when the CloseHandle(handle) is called? - This function first checks the calling process’s handle table to ensure that the index (handle) passed to it identifies an object that the process does in fact have access to. If the index is valid, the system gets the address of the kernel object’s data structure and decrements the usage count member in the structure; if the count is zero, the kernel destroys the kernel object from memory.
  17. You forget to call CloseHandle - will there be a memory leak? - Well, yes and no. It is possible for a process to leak resources (such as kernel objects) while the process runs. However, when the process terminates, the operating system ensures that any and all resources used by the process are freed—this is guaranteed. For kernel objects, the system performs the following actions: When your process terminates, the system automatically scans the process’s handle table. If the table has any valid entries (objects that you didn’t close before terminating), the system closes these object handles for you. If the usage count of any of these objects goes to zero, the kernel destroys the object.
  18. What is the need of process relative handles? - The most important reason was robustness. If kernel object handles were system-wide values, one process could easily obtain the handle to an object that another process was using and wreak havoc on that process. Another reason for process-relative handles is security. Kernel objects are protected with security, and a process must request permission to manipulate an object before attempting to manipulate it. The creator of the object can prevent an unauthorized user from touching the object simply by denying access to it
  19. How the handles are handled in the child process? - The operating system creates the new child process but does not allow the child process to begin executing its code right away. Of course, the system creates a new, empty process handle table for the child process—just as it would for any new process. But because you passed TRUE to CreateProcess’s bInheritHandles parameter, the system does one more thing: it walks the parent process’s handle table, and for each entry it finds that contains a valid inheritable handle, the system copies the entry exactly into the child process’s handle table. The entry is copied to the exact same position in the child process’s handle table as in the parent’s handle table.
  20. Why the entries in the parent process table and child table are same? - It means that the handle value that identifies a kernel object is identical in both the parent and the child processes.
  21. What about the usage count in the parent child process tables? - The system increments the usage count of the kernel object because two processes are now using the object. For the kernel object to be destroyed, both the parent process and the child process must either call CloseHandle on the object or terminate.
  22. What are Named Objects? - Method available for sharing kernel objects across process boundaries is to name the objects. Below are the kernel named objects 1) mutex, 2) Events, 3) semaphore, 4) waitableTimers, 5)file mapping, 6)job object. There are APIs to create these objects with last parameter as the object name.
  23. What do you mean by unnamed object? - When you are creating the kernel objects with the help of API’s like CreateMutex(, , , ,pzname). And the Pzname parameter is NULL , you are indicating to the system that you want to create an unnamed (anonymous) kernel object. When you create an unnamed object, you can share the object across processes by using either inheritance or DuplicateHandle
  24. What is DuplicateHandle (API)? - Takes an entry in one process’s handle table and makes a copy of the entry into another process’s handle table
  25. What is a thread? - A thread describes a path of execution within a process. Every time a process is initialized, the system creates a primary thread. This thread begins executing with the C/C++ run-time library’s startup code, which in turn calls your entry-point function ( main , Wmain , WinMain , or WWinMain ) and continues executing until the entry-point function returns and the C/C++ run-time library’s startup code calls ExitProcess
  26. What is the limit on per process for creating a thread? - The number of threads a process can create is limited by the available virtual memory and depends on the default stack size
  27. What is Synchronization Objects? - Synchronization object s are use to co-ordinate the execution of multiple threads.
  28. Which kernel objects are use for Thread Synchronization on different processes? - Event, Mutex, Semaphore
  29. What is Event Object and why it is used? - Event is the thread synchronization object to set signaled state or non-signaled state.
  30. What is signaled and non signaled state? - An event is in signaled state means that it has the capacity to release the threads waiting for this event to be signaled. An event is in non signaled state means that it will not release any thread that is waiting for this particular event.example in our project: when user clicks the image application icon double simultaneously. Two image application windows were created. so PAIG created an event and set it to non-signaled state. Then the image application will reset the event to signaled state, after this all the threads are released.
  31. APIs for creating event and set and reset the events - CreateEvent-to create the event OpenEvent – to open already created event SetEvent – to set the event signaled stateRestEvent - To set the Event To non-Signaled State
  32. What is Mutex Object and why it is used? - A mutex object is a synchronization object whose state is set to signaled when it is not owned by any thread, and non-signaled when it is owned. For example, to prevent two threads from writing to shared memory at the same time, each thread waits for ownership of a mutex object before executing the code that accesses the memory. After writing to the shared memory, the thread releases the mutex object.
  33. How do I create a Mutex? - A thread uses the CreateMutex function to create a mutex object. The creating thread can request immediate ownership of the mutex object and can also specify a name for the mutex object
  34. How do other threads own the mutex? - Threads in other processes can open a handle to an existing named mutex object by specifying its name in a call to theOpenMutex - function. Any thread with a handle to a mutex object can use one of the wait functions to request ownership of the mutex object. If the mutex object is owned by another thread, the wait function blocks the requesting thread until the owning thread releases the mutex object using theReleaseMutex - function.
  35. What is semaphores and why it is used? - A semaphore object is a synchronization object that maintains a count between zero and a specified maximum value. The count is decremented each time a thread completes a wait for the semaphore object and incremented each time a thread releases the semaphore. When the count reaches zero, no more threads can successfully wait for the semaphore object state to become signaled. The state of a semaphore is set to signaled when its count is greater than zero, and non-signaled when its count is zero. The semaphore object is useful in controlling a shared resource that can support a limited number of users. It acts as a gate that limits the number of threads sharing the resource to a specified maximum number. For example, an application might place a limit on the number of windows that it creates. It uses a semaphore with a maximum count equal to the window limit, decrementing the count whenever a window is created and incrementing it whenever a window is closed. The application specifies the semaphore object in call to one of the wait functions before each window is created. When the count is zero - indicating that the window limit has been reached - the wait function blocks execution of the window-creation code.

C & C++ Questions for interviews



  1. What is the output of printf(”%d”)
  2. What will happen if I say delete this
  3. Difference between “C structure” and “C++ structure”.
  4. Diffrence between a “assignment operator” and a “copy constructor”
  5. What is the difference between “overloading” and “overridding”?
  6. Explain the need for “Virtual Destructor”.
  7. Can we have “Virtual Constructors”?
  8. What are the different types of polymorphism?
  9. What are Virtual Functions? How to implement virtual functions in “C”
  10. What are the different types of Storage classes?
  11. What is Namespace?
  12. What are the types of STL containers?.
  13. Difference between “vector” and “array”?
  14. How to write a program such that it will delete itself after exectution?
  15. Can we generate a C++ source code from the binary file?
  16. What are inline functions?
  17. What is “strstream” ?
  18. Explain “passing by value”, “passing by pointer” and “passing by reference”
  19. Have you heard of “mutable” keyword?
  20. What is a “RTTI”?
  21. Is there something that I can do in C andnot in C++What is the difference between “calloc” and “malloc”?
  22. What will happen if I allocate memory using “new” and free it using “free” or allocate sing “calloc” and free it using “delete”?
  23. Difference between “printf” and “sprintf”.
  24. What is “map” in STL?
  25. When shall I use Multiple Inheritance?
  26. Explain working of printf.
  27. Talk sometiming about profiling?
  28. How many lines of code you have written for a single program?
  29. How to write Multithreaded applications using C++?
  30. Write any small program that will compile in “C” but not in “C++”
  31. What is Memory Alignment?
  32. Why preincrement operator is faster than postincrement?
  33. What are the techniques you use for debugging?
  34. How to reduce a final size of executable?
  35. Give 2 examples of a code optimization.