C++ interview questions & Answers

C++ interview questions


  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++ object-oriented interview questions

1.    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++ algorithms interview questions from Microsoft and IB

1.    (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 interview questions

1.    1. How do you write a function that can reverse a linked-list? (Cisco System)
2.  void reverselist(void)
3.  {
4.    if(head==0)
5.           return;
6.    if(head->next==0)
7.           return;
8.    if(head->next==tail)
9.    {
10.         head->next = 0;
11.         tail->next = head;
12.  }
13.  else
14.  {
15.         node* pre = head;
16.         node* cur = head->next;
17.         node* curnext = cur->next;
18.         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++ networking questions

1.    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++ algorithm specific interview questions

1.    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
Basic C++ interview questions

1.    1.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
C++ coding interview questions

1.    . 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();

Advanced C++ and STL interview questions

1.    Q: 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++ programming on UNIX platforms

  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 not.
Basic C++ and UNIX OS programming

1.    Q1: Could you tell something about the Unix System Kernel? (from ITCO )
A1: The kernel is the heart of the UNIX openrating system, it’s reponsible for controlling the computer’s resouces and scheduling user jobs so that each one gets its fair share of resources.
Q2: What are each of the standard files and what are they normally associated with? (from ITCO )
A2: They are the standard input file, the standard output file and the standard error file. The first is usually associated with the keyboard, the second and third are usually associated with the terminal screen.


Q3: Detemine the code below, tell me exectly how many times is the operation sum++ performed ? (from ITCO )
for ( i = 0; i < 100; i++ )
for ( j = 100; j > 100 - i; j–)
sum++;
A3: (99 * 100)/2 = 4950
The sum++ is performed 4950 times.
Q4: Give 4 examples which belongs application layer in TCP/IP architecture? (from CISCO )
A4: FTP, TELNET, HTTP and TFTP
Q5: What’s the meaning of ARP in TCP/IP? (from CISCO )
A5: The "ARP" stands for Address Resolution Protocol. The ARP standard defines two basic message types: a request and a response. a request message contains an IP address and requests the corresponding hardware address; a replay contains both the IP address, sent in the request, and the hardware address.

Related

C++ AND OOPS 6532899809392058186

Post a Comment

emo-but-icon

Follow Us

Hot in week

Comments

Side Ads

Text Widget

All data and information provided on this blog is for informational purposes only. This weblog makes no representations as to accuracy, completeness, currentness, suitability, or validity of any information on this site or found by following any link on this site. The owner will not be liable for any errors, omissions, or delays in this information or any losses, injuries, or damages arising from its display or use. All information is provided on an as-is basis.

Connect Us

Enter your email address:

Delivered by FeedBurner

item