Vous êtes sur la page 1sur 35

Software testing - Questions and Answers - Linix / Unix

1. Q. How do you list files in a directory?


A. ls - list directory contents
ls ???l (-l use a long listing format)

2. Q. How do you list all files in a directory, including the hidden files?
A. ls -a (-a, do not hide entries starting with .)

3. Q. How do you find out all processes that are currently running?
A. ps -f (-f does full-format listing.)

4. Q. How do you find out the processes that are currently running or a
particular user?
A. ps -au Myname (-u by effective user ID (supports names)) (a - all
users)

5. Q. How do you kill a process?


A. kill -9 8 (process_id 8) or kill -9 %7 (job number 7)
kill -9 -1 (Kill all processes you can kill.)
killall - kill processes by name most (useful - killall java)

6. Q. What would you use to view contents of the file?


A. less filename
cat filename
pg filename
pr filename
more filename
most useful is command: tail file_name - you can see the end of the
log file.
7. Q. What would you use to edit contents of the file?
A. vi screen editor or jedit, nedit or ex line editor

8. Q. What would you use to view contents of a large error log file?
A. tail -10 file_name ( last 10 rows)

9. Q. How do you log in to a remote Unix box?


A. Using telnet server_name or ssh -l ( ssh - OpenSSH SSH client (remote
login program))

10.Q. How do you get help on a UNIX terminal?


A. man command_name
info command_name (more information)

11.Q. How do you list contents of a directory including all of its


subdirectories, providing full details and sorted by modification time?
A. ls -lac
-a all entries
-c by time

12.Q. How do you create a symbolic link to a file (give some reasons of
doing so)?
A. ln /../file1 Link_name
Links create pointers to the actual files, without duplicating the contents
of
the files. That is, a link is a way of providing another name to the same
file.
There are two types of links to a file:Hard link, Symbolic (or soft) link;

13.Q. What is a filesystem?


A. Sum of all directories called file system.
A file system is the primary means of file storage in UNIX.
File systems are made of inodes and superblocks.

14.Q. How do you get its usage (a filesystem)?


A. By storing and manipulate files.

15.Q. How do you check the sizes of all users??? home


directories (one command)?
A. du -s
df

The du command summarizes disk usage by directory. It recurses through all


subdirectories and shows disk usage by each subdirectory with a final total
at the end.

Q. in current directory
A. ls -ps (p- directory; s - size)

16.Q. How do you check for processes started by user 'pat'?

A. ps -fu pat (-f -full_format u -user_name )

17.Q. How do you start a job on background?

A. bg %4 (job 4)

18 Q. What utility would you use to replace a string '2001' for '2002' in a
text file?

A. Grep, Kde( works on Linux and Unix)

19. Q. What utility would you use to cut off the first column in a text file?
A. awk, kde

20. Q. How to copy file into directory?


A. cp /tmp/file_name . (dot mean in the current directory)

21. Q. How to remove directory with files?


A. rm -rf directory_name

22. Q. What is the difference between internal and external commands?


A. Internal commands are stored in the; same level as the operating
system while external
commands are stored on the hard disk among the other utility programs.

23. Q. List the three main parts of an operating system command:


A. The three main parts are the command, options and arguments.

24 Q. What is the difference between an argument and an option (or switch)?


A. An argument is what the command should act on: it could be a filename,
directory or name. An option is specified when you want to request
additional
information over and above the basic information each command supplies.

25. Q. What is the purpose of online help?


A. Online help provides information on each operating system command,
the
syntax, the options, the arguments with descriptive information.
26. Q. Name two forms of security.
A. Two forms of security are Passwords and File Security with
permissions specified.

27. Q. What command do you type to find help about the command who?
A. $ man who
28. Q. What is the difference between home directory and working directory?
A. Home directory is the directory you begin at when you log into the
system. Working directory can be anywhere on the system and it is where you
are currently
working.

29. Q. Which directory is closer to the top of the file system tree, parent
directory or current directory?
A. The parent directory is above the current directory, so it is closer
to
the root or top of the
file system.

30. Q. Given the following pathname:


$ /business/acctg/payable/supplier/april
a) If you were in the directory called acctg, what would be the relative
pathname name for the file called april?
b) What would be the absolute pathname for april?
A.
a) $ payable/supplier/april
b) $ /business/acctg/payable/supplier/april

31. Q. Suppose your directory had the following files:


help. 1 help.2 help.3 help.4 help.O1 help.O2
aid.O1 aid.O2 aid.O3 back. 1 back.2 back.3
a) What is the command to list all files ending in 2?
b) What is the command to list all files starting in aid?
c) What is the command to list all "help" files with one character extension?
A.
a) ls *2
b) ls aid.*
c) ls help.?

32. Q. What are two subtle differences in using the more and the pg commands?
A. With the more command you display another screenful by pressing
the spacebar, with pg you press the return key.
The more command returns you automatically to the UNIX
shell when completed, while pg waits until you press return.

33. Q. When is it better to use the more command rather than cat command?
A. It is sometimes better to use the more command when you are viewing
a file that will display over one screen.

34. Q. What are two functions the move mv command can carry out?
A. The mv command moves files and can also be used to rename a file or
directory.

35. Q. Name two methods you could use to rename a file.


A. Two methods that could be used:
a. use the mv command
b. copy the file and give it a new name and then remove the original file if
no longer needed.

36. The soccer league consists of boy and girl teams. The boy file names
begin
with B, the girl teams begin with G. All of these files are in one directory
called "soccer", which is your current directory:
Bteam.abc Bteam.OOl Bteam.OO2 Bteam.OO4
Gteam.win Gteam.OOl Gteam.OO2 Gteam.OO3
Write the commands to do the following:
a) rename the file Bteam.abc to Bteam.OO3.
b) erase the file Gteam. win after you have viewed the contents of the file
c) make a directory for the boy team files called "boys", and one for the
girl team files
called" girls"
d) move all the boy teams into the "boys" directory
e) move all the girl teams into the "girls" directory
f) make a new file called Gteam.OO4 that is identical to Gteam.OOl
g) make a new file called Gteam.OO5 that is identical to Bteam.OO2
A.
a) mv Bteam.abc Bteam.OO3.
b) cat Gteam.win -or- more Gteam.win
rm Gteam. win
c) mkdir boys
mkdir girls
d) mv Bteam* boys
e) mv Gteam* girls
f) cd girls
cp Gteam.OO1 Gteam.OO4
g) There are several ways to do this. Remember that we are currently in the
directory
/soccer/girls.
cp ../boys/Bteam.OO2 Gteam.OO5
or
cd ../boys
cp Bteam.OO2 ../girls/Gteam.OO5

37. Q. Draw a picture of the final directory structure for the "soccer"
directory, showing all the files and directories.

38. Q. What metacharacter is used to do the following:


1.1 Move up one level higher in the directory tree structure
1.2 Specify all the files ending in .txt
1.3 Specify one character
1.4 Redirect input from a file
1.5 Redirect the output and append it to a file
A.
1. 1.1 double-dot or ..
1.2 asterisk or *
1.3 question or ?
1.4 double greater than sign: >>
1.5 the less than sign or <

39. Q. List all the files beginning with A


A. To list all the files beginning with A command: ls A*

40. Q. Which of the quoting or escape characters allows the dollar sign ($)
to retain its special meaning?
A. The double quote (") allows the dollar sign ($) to retain its special
meaning.
Both the backslash (\) and single quote (') would remove the special meaning
of the dollar sign.

41. Q. What is a faster way to do the same command?


mv fileO.txt newdir
mv filel.txt newdir
mv file2.txt newdir
mv file3.txt newdir
A. A shortcut method would be: mv file?.txt newdir

42. Q. List two ways to create a new file:


A.
a. Copy a file to make a new file.
b. Use the output operator e.g. ls -l > newfile.txt

43. Q. What is the difference between > and >> operators?


A. The operator > either overwrites the existing file (WITHOUT WARNING)
or creates a new file.
The operator >> either adds the new contents to the end of an existing file
or creates a new file.

44. Write the command to do the following:


44.1 Redirect the output from the directory listing to a printer.
44.2 Add the file efg.txt to the end of the file abc.txt.
44.3 The file testdata feeds information into the file called program
44.4 Observe the contents of the file called xyz.txt using MORE.
44.5 Observe a directory listing that is four screens long.
A.
44.1 ls > lpr
44.2 cat efg.txt >> abc.txt
44.3 program < testdata
44.4 more < xyz.txt
44.5 ls > dirsave | more

45. Q. How do you estimate file space usage


A. Use du command (Summarize disk usage of each FILE, recursively for
directories.) Good to use arguments du -hs
(-h, --human-readable print sizes in human readable format (e.g., 1K 234M 2G
)
(-s, --summarize display only a total for each argument)
46. Q. How can you see all mounted drives?
A. mount -l

47. Q. How can you find a path to the file in the system?
A. locate file_name (locate - list files in databases that match a
pattern)

48. Q. What Linux HotKeys do you know?


A. Ctrl-Alt-F1 Exit to command prompt
Ctrl-Alt-F7 or F8 Takes you back to KDE desktop from command
prompt
Crtl-Alt-Backspace Restart XWindows
Ctrl-Alt-D Show desktop

49. Q. What can you tell about the tar Command?


A. The tar program is an immensely useful archiving utility. It can
combine
an entire directory tree into one large file suitable for transferring or
compression.

50. Q. What types of files you know?


A. Files come in eight flavors:
Normal files
Directories
Hard links
Symbolic links
Sockets
Named pipes
Character devices
Block devices
51. Q. How to copy files from on PC to another on the same network
A. Use the following command:scp yur_file you_login@your_IP
example: copy .conf file from your PC to alex computer-
scp /etc/X11/xorg.conf alex@10.0.10.169:

52. Q. Please describe information below:

-rw-rw-r-- 1 dotpc dotpc 102 Jul 18 2003 file.buf


drwxr-xr-x 9 dotpc dotpc 4096 Oct 21 09:34 bin
lrwxrwxrwx 1 dotpc dotpc 20 Mar 21 15:00 client -> client-2.9
.5
drwxrwxr-x 11 dotpc dotpc 4096 Sep 2 2005 client-2.8.9
drwxrwxr-x 7 dotpc dotpc 4096 Dec 14 12:13 data
drwxr-xr-x 12 dotpc dotpc 4096 Oct 21 09:41 docs
drwxr-xr-x 5 dotpc dotpc 4096 Dec 7 14:22 etc
drwxr-xr-x 11 dotpc dotpc 4096 Mar 21 15:54 client-2.9.5
-rw-r--r-- 1 dotpc dotpc 644836 Mar 22 09:53 client-2.9.5.tar.gz

A. This is a result of command $ls -l


we have two files, 6 directories and one link to client-2.9.5 directory.
There is number of files in every directory, size and data of last change.

53. Q. If you would like to run two commands in sequence what operators you
can use?

A. ; or && the difference is:


if you separate commands with ; second command will be run automatically.
if you separate commands with && second command will be run only in the case
the first was run successfully.
54. Q. How you will uncompress the file?
A. Use tar command (The GNU version of the tar archiving utility):
tar -zxvf file_name.tar.gz

55. Q.How do you execute a program or script, my_script in your current


directoty?
A. ./my_script

56. Q.How to find current time configuration in the file my_new.cfg


A. grep time my_new.cfg
Grep searches the named input files (or standard input if
no files are named, or the file name - is given) for lines
containing a match to the given pattern.

Q. What does grep() stand for?


A. General Regular Expression Parser.

57. Q. What does the top command display?


A. Top provides an ongoing look at processor activity in real
time. It displays a listing of the most CPU-intensive
tasks on the system, and can provide an interactive inter?
face for manipulating processes. (q is to quit)

58. Q. How can you find configuration on linux?


A. by using /sin/ifconfig
If no arguments are given, ifconfig displays the status of the cur-
rently active interfaces. If a single interface argument is given, it
displays the status of the given interface only; if a single -a argu-
ment is given, it displays the status of all interfaces, even those
that are down. Otherwise, it configures an interface.
59. Q. How to find difference in two configuration files on the same server?
A. Use diff command that is compare files line by line
diff -u /usr/home/my_project1/etc/ABC.conf /usr/home/my_project2/etc/ABC.
conf

60. Q. What is the best way to see the end of a logfile.log file?
A. Use tail command - output the last part of files
tail -n file_name ( the last N lines, instead of the last 10 as default)

61. Q. Please write a loop for removing all files in the current directory
that contains a word 'log'
A. for i in *log*; do rm $i; done

62. Question: How to switch to a previously used directory?


Answer: cd -

1. Q.How many VI editor modes do you know?


A.Three modes -
Command mode: letters or sequence of letters interactively command vi.
Insert mode: Text is inserted.
Command line mode: enter this mode by typing ":" and entry command line at
the foot of the screen.

2. Q. How can you terminate VI session?


A.

¡¤ Use command: ZZ that is save changes and quit.

¡¤ Use command line: ":wq" that is write changes and quit.

¡¤ Use command line: ":q!" to ignore changes and quit.


3. Q. How can you copy lines into the buffer in command mode?
A.
yy - copy a single line defined by current cursor position
3yy - copy 3 lines. Current line and two lines below it.

Unix/Linux programming interview questions


Question 1: What is the major advantage of a hash table? (Asked by Silicon
Magic Corp. people)
Answer: The major advantage of a hash table is its speed. Because the hash
function is to take a range of key values and transform them into index
values in such a way that the key values are distributed randomly across all
the indices of a hash table.
Question 2: What are the techniques that you use to handle the collisions in
hash tables?(Asked by Silicon Magic Corp. people)
Answer: We can use two major techniques to handle the collisions. They are
open addressing and separate chaining. In open addressing, data items that
hash to a full array cell are placed in another cell in the array. In
separate chaining, each array element consist of a linked list. All data
items hashing to a given array index are inserted in that list.
Question 3: In Unix OS, what is the file server? (Asked by Silicon Magic
Corp. people)
Answer: The file server is a machine that shares its disk storage and files
with other machines on the network.
Question 4: What is NFS? What is its job?(Asked by Silicon Magic Corp.
people)
Answer: NFS stands for Network File System. NFS enables filesystems
physically residing on one computer system to be used by other computers in
the network, appearing to users on the remote host as just another local
disk.
Question 5: What is CVS? List some useful CVS commands.(Asked by Silicon
Magic Corp.people)
Anser: CVS is Concurrent Version System. It is the front end to the RCS
revision control system which extends the notion of revision control from a
collection of files in a single directory to a hierarchical collection of
directories consisting of revision controlled files. These directories and
files can be combined together to form a software release.
There are some useful commands that are being used very often. They are
cvs checkout
cvs update
cvs add
cvs remove
cvs commit

^Back to Top
Unix/Linux administration interview questions
What is LILO?
LILO stands for Linux boot loader. It will load the MBR, master boot record,
into the memory, and tell the system which partition and hard drive to boot
from.
What is the main advantage of creating links to a file instead of copies of
the file?
A: The main advantage is not really that it saves disk space (though it does
that too) but, rather, that a change of permissions on the file is applied
to all the link access points. The link will show permissions of lrwxrwxrwx
but that is for the link itself and not the access to the file to which the
link points. Thus if you want to change the permissions for a command, such
as su, you only have to do it on the original. With copies you have to find
all of the copies and change permission on each of the copies.
Write a command to find all of the files which have been accessed within the
last 30 days.
find / -type f -atime -30 > December.files
This command will find all the files under root, which is ¡®/¡‾, with file
type is file. ¡®-atime -30¡ä will give all the files accessed less than 30
days ago. And the output will put into a file call December.files.
What is the most graceful way to get to run level single user mode?
A: The most graceful way is to use the command init s.
If you want to shut everything down before going to single user mode then do
init 0 first and from the ok prompt do a boot -s.
What does the following command line produce? Explain each aspect of this
line.
$ (date ; ps -ef | awk ¡®{print $1}¡‾ | sort | uniq | wc -l ) >> Activity.
log
A: First let¡‾s dissect the line: The date gives the date and time as the
first command of the line, this is followed by the a list of all running
processes in long form with UIDs listed first, this is the ps -ef. These are
fed into the awk which filters out all but the UIDs; these UIDs are piped
into sort for no discernible reason and then onto uniq (now we see the
reason for the sort - uniq only works on sorted data - if the list is A, B,
A, then A, B, A will be the output of uniq, but if it¡‾s A, A, B then A, B
is the output) which produces only one copy of each UID.
These UIDs are fed into wc -l which counts the lines - in this case the
number of distinct UIDs running processes on the system. Finally the results
of these two commands, the date and the wc -l, are appended to the file "
Activity.log". Now to answer the question as to what this command line
produces. This writes the date and time into the file Activity.log together
with the number of distinct users who have processes running on the system
at that time. If the file already exists, then these items are appended to
the file, otherwise the file is created.
1. How do you list the files in an UNIX directory while also showing
hidden files? ls -ltra
2. How do you execute a UNIX command in the background? Use the ¡°&¡±.
3. What UNIX command will control the default file permissions when files
are created? umask
4. Explain the read, write, and execute permissions on a UNIX directory.
Read allows you to see and list the directory contents. Write allows you to
create, edit and delete files and subdirectories in the directory. Execute
gives you the permissions to run programs or shells from the directory.
5. What is the difference between a soft link and a hard link? A symbolic
(soft) linked file and the targeted file can be located on the same or
different file system while for a hard link they must be located on the same
file system.
6. Give the command to display space usage on the UNIX file system. df -
lk
7. Explain iostat, vmstat and netstat. iostat reports on terminal, disk
and tape I/O activity. vmstat reports on virtual memory statistics for
processes, disk, tape and CPU activity. netstat reports on the contents of
network data structures.
8. How would you change all occurrences of a value using VI? %s/(old
value)/(new value)/g
9. Give two UNIX kernel parameters that effect an Oracle install. SHMMAX
& SHMMNI
10. Briefly, how do you install Oracle software on UNIX? Basically, set up
disks, kernel parameters, and run orainst.
C++ Interview Questions
C++ code examples for job interviews
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 << i<<",";
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"<<average<<endl;
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.

^Back to Top
C++ object-oriented 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

^Back to Top
Interview questions on C/C++
A reader submitted the interview questions he was asked. More C/C++
questions will be added here, as people keep sending us a set of 2-3
questions they got on their job itnerview.
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 ("circular\n");
}
}
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 <stdio.h>
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 & Y) | (X & Z) | (Y & Z)

^Back to Top
C++ gamedev interview questions
This set of questions came from a prominent gaming company. As you can see,
the answers are not given (the interviews are typically conducted by senior
developers), but there¡‾s a set of notes with common mistakes to avoid.
1. Explain which of the following declarations will compile
and what will be constant - a pointer or the value pointed at:
o const char *
o char const *
o char * const
Note: Ask the candidate whether the first declaration is pointing to a
string or a single character. Both explanations are correct, but if he says
that it¡‾s a single character pointer, ask why a whole string is initialized
as char* in C++. If he says this is a string declaration, ask him to
declare a pointer to a single character. Competent candidates should not
have problems pointing out why const char* can be both a character and a
string declaration, incompetent ones will come up with invalid reasons.
2. You¡‾re given a simple code for the class BankCustomer.
Write the following functions:
o Copy constructor
o = operator overload
o == operator overload
o + operator overload (customers¡‾
balances should be added up, as an example of joint account between husband
and wife)
Note:Anyone confusing assignment and equality operators should be dismissed
from the interview. The applicant might make a mistake of passing by value,
not by reference. The candidate might also want to return a pointer, not a
new object, from the addition operator. Slightly hint that you¡‾d like the
value to be changed outside the function, too, in the first case. Ask him
whether the statement customer3 = customer1 + customer2 would work in the
second case.
3. What problems might the following macro bring to the
application?
#define sq(x) x*x
4. Consider the following struct declarations:
5. struct A { A(){ cout << "A"; } };
6. struct B { B(){ cout << "B"; } };
7. struct C { C(){ cout << "C"; } };
8. struct D { D(){ cout << "D"; } };
9. struct E : D { E(){ cout << "E"; } };
10. struct F : A, B
11. {
12. C c;
13. D d;
14. E e;
15. F() : B(), A(),d(),c(),e() { cout << "F"; }
};
What constructors will be called when an instance of F is initialized?
Produce the program output when this happens.
16. Anything wrong with this code?
17. T *p = new T[10];
18. delete p;

Note: Incorrect replies: ¡°No, everything is correct¡±, ¡°Only the first


element of the array will be deleted¡±, ¡°The entire array will be deleted,
but only the first element destructor will be called¡±.
19. Anything wrong with this code?
20. T *p = 0;
21. delete p;
Note: Typical wrong answer: Yes, the program will crash in an attempt to
delete a null pointer. The candidate does not understand pointers. A very
smart candidate will ask whether delete is overloaded for the class T.
22. Explain virtual inheritance. Draw the diagram explaining the
initialization of the base class when virtual inheritance is used.
Note: Typical mistake for applicant is to draw an inheritance diagram, where
a single base class is inherited with virtual methods. Explain to the
candidate that this is not virtual inheritance. Ask them for the classic
definition of virtual inheritance. Such question might be too complex for a
beginning or even intermediate developer, but any applicant with advanced C+
+ experience should be somewhat familiar with the concept, even though he¡‾
ll probably say he¡‾d avoid using it in a real project. Moreover, even the
experienced developers, who know about virtual inheritance, cannot
coherently explain the initialization process. If you find a candidate that
knows both the concept and the initialization process well, he¡‾s hired.
23. What¡‾s potentially wrong with the following code?
24.
25. long value;
26. //some stuff
27. value &= 0xFFFF;
Note: Hint to the candidate about the base platform they¡‾re developing for.
If the person still doesn¡‾t find anything wrong with the code, they are
not experienced with C++.
28. What does the following code do and why would anyone write
something like that?
29. void send (int *to, int * from, int count)
30. {
31. int n = (count + 7) / 8;
32. switch ( count % 8)
33. {
34. case 0: do { *to++ = *from++;
35. case 7: *to++ = *from++;
36. case 6: *to++ = *from++;
37. case 5: *to++ = *from++;
38. case 4: *to++ = *from++;
39. case 3: *to++ = *from++;
40. case 2: *to++ = *from++;
41. case 1: *to++ = *from++;
42. } while ( --n > 0 );
43. }
44. }
45. In the H file you see the following declaration:
46. class Foo {
47. void Bar( void ) const ;
48. };
Tell me all you know about the Bar() function.

1. Is it possible to have Virtual Constructor? If yes, how? If not,


Why not possible ?
There is nothing like Virtual Constructor. The Constructor cant be virtual
as the constructor is a code which is responsible for creating a instance of
a class and it cant be delegated to any other object by virtual keyword
means.
2. What about Virtual Destructor?
Yes there is a Virtual Destructor. A destructor can be virtual as it is
possible as at runtime depending on the type of object baller is balling to
, proper destructor will be called.
3. What is Pure Virtual Function? Why and when it is used ?
The abstract class whose pure virtual method has to be implemented by all
the classes which derive on these. Otherwise it would result in a
compilation error.
This construct should be used when one wants to ensure that all the derived
classes implement the method defined as pure virtual in base class.
4. What is problem with Runtime type identification?
The run time type identification comes at a cost of performance penalty.
Compiler maintains the class.
5. How Virtual functions call up is maintained?
Through Look up tables added by the compile to every class image. This also
leads to performance penalty.
6. Can inline functions have a recursion?
No.
Syntax wise It is allowed. But then the function is no longer Inline. As the
compiler will never know how deep the recursion is at compilation time.
7. How do you link a C++ program to C functions?
By using the extern "C" linkage specification around the C function
declarations.
Programmers should know about mangled function names and type-safe linkages.
Then they should explain how the extern "C" linkage specification statement
turns that feature off during compilation so that the linker properly links
function calls to C functions.
8. Explain the scope resolution operator?
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.
9. How many ways are there to initialize an int with a constant?
1. int foo = 123;
2. int bar(123);
10. What is your reaction to this line of code? delete this;
It is not a good programming Practice.
A good programmer will insist that you should absolutely never use the
statement if the class is to be used by other programmers and instantiated
as static, extern, or automatic objects. That much should be obvious.
The code has two built-in pitfalls. First, if it executes in a member
function for an extern, static, or automatic object, the program will
probably crash as soon as the delete statement executes. There is no
portable way for an object to tell that it was instantiated on the heap, so
the class cannot assert that its object is properly instantiated. Second,
when an object commits suicide this way, the using program might not know
about its demise. As far as the instantiating program is concerned, the
object remains in scope and continues to exist even though the object did
itself in. Subsequent dereferencing of the baller can and usually does lead
to disaster. I think that the language rules should disallow the idiom, but
that's another matter.
11. What is the difference between a copy constructor and an overloaded
assignment operator?
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.
12. When should you use multiple inheritance?
There are three acceptable answers:- "Never," "Rarely," and "When the
problem domain cannot be accurately modeled any other way."
Consider an Asset class, Building class, Vehicle class, and CompanyCar class
. All company cars are vehicles. Some company cars are assets because the
organizations own them. Others might be leased. Not all assets are vehicles.
Money accounts are assets. Real estate holdings are assets. Some real
estate holdings are buildings. Not all buildings are assets. Ad infinitum.
When you diagram these relationships, it becomes apparent that multiple
inheritance is a likely and intuitive way to model this common problem
domain. The applicant should understand, however, that multiple inheritance,
like a chainsaw, is a useful tool that has its perils, needs respect, and
is best avoided except when nothing else will do.
13. What is a virtual destructor?
The simple answer is that a virtual destructor is one that is declared with
the virtual attribute.
The behavior of a virtual destructor is what is important. If you destroy an
object through a baller or reference to a base class, and the base-class
destructor is not virtual, the derived-class destructors are not executed,
and the destruction might not be comple
14. Can a constructor throw a exception? How to handle the error when the
constructor fails?
The constructor never throws a error.
15. What are the debugging methods you use when came across a problem?
Debugging with tools like :
GDB, DBG, Forte, Visual Studio.
Analyzing the Core dump.
Using tusc to trace the last system call before crash.
Putting Debug statements in the program source code.
16. How the compilers arranges the various sections in the executable
image?
The executable had following sections:-
Data Section (uninitialized data variable section, initialized data variable
section )
Code Section
Remember that all static variables are allocated in the initialized variable
section.
17. Explain the ISA and HASA class relationships. How would you implement
each in a class design?
A specialized class "is" a specialization of another class and, therefore,
has the ISA relationship with the other class.
This relationship is best implemented by embedding an object of the Salary
class in the Employee class.
18. When is a template a better solution than a base class?
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 generality) to the designer of the
container or manager class.
19. What are the differences between a C++ struct and C++ class?
The default member and base-class access specifies are different.
This is one of the commonly misunderstood aspects of C++. Believe it or not,
many programmers think that a C++ struct is just like a C struct, while a C
++ class has inheritance, access specifies, member functions, overloaded
operators, and so on. Actually, the C++ struct has all the features of the
class. The only differences are that a struct defaults to public member
access and public base-class inheritance, and a class defaults to the
private access specified and private base-class inheritance.
20. How do you know that your class needs a virtual destructor?
If your class has at least one virtual function, you should make a
destructor for this class virtual. This will allow you to delete a dynamic
object through a baller to a base class object. If the destructor is non-
virtual, then wrong destructor will be invoked during deletion of the
dynamic object.
21. What is the difference between new/delete and malloc/free?
Malloc/free do not know about constructors and destructors. New and delete
create and destroy objects, while malloc and free allocate and deallocate
memory.
22. What happens when a function throws an exception that was not
specified by an exception specification for this function?
Unexpected() is called, which, by default, will eventually trigger abort().
23. Can you think of a situation where your program would crash without
reaching the breakball, which you set at the beginning of main()?
C++ allows for dynamic initialization of global variables before main() is
invoked. It is possible that initialization of global will invoke some
function. If this function crashes the crash will occur before main() is
entered.
24. What issue do auto_ptr objects address?
If you use auto_ptr objects you would not have to be concerned with heap
objects not being deleted even if the exception is thrown.
25. Is there any problem with the following:
char *a=NULL; char& p = *a;?
The result is undefined. You should never do this. A reference must always
refer to some object.
26. Why do C++ compilers need name mangling?
Name mangling is the rule according to which C++ changes function's name
into function signature before passing that function to a linker. This is
how the linker differentiates between different functions with the same name.
27. Is there anything you can do in C++ that you cannot do in C?

No. There is nothing you can do in C++ that you cannot do in C. After all
you can write a C++ compiler in C

¡¤ What are the major differences between C and C++?


o What are the differences between
new and malloc?
o What is the difference between
delete and delete[]?
o What are the differences between a
struct in C and in C++?
o What are the advantages/
disadvantages of using #define?
o What are the advantages/
disadvantages of using inline and const?
¡¤ What is the difference between a baller and a reference?
o When would you use a baller? A
reference?
o What does it mean to take the
address of a reference?
¡¤ What does it mean to declare a function or variable as
static?
¡¤ What is the order of initalization for data?
¡¤ What is name mangling/name decoration?
o What kind of problems does name
mangling cause?
o How do you work around them?
¡¤ What is a class?
o What are the differences between a
struct and a class in C++?
o What is the difference between
public, private, and protected access?
o For class CFoo { }; what default
methods will the compiler generate for you>?
o How can you force the compiler to
not generate them?
o What is the purpose of a
constructor? Destructor?
o What is a constructor initializer
list?
o When must you use a constructor
initializer list?
o What is a:
¡ì
Constructor?
¡ì Destructor?
¡ì Default
constructor?
¡ì Copy
constructor?
¡ì Conversion
constructor?
o What does it mean to declare a...
¡ì member
function as virtual?
¡ì member
function as static?
¡ì member
function as static?
¡ì member
variable as static?
¡ì destructor
as static?
o Can you explain the term "resource
acquisition is initialization?"
o What is a "pure virtual" member
function?
o What is the difference between
public, private, and protected inheritance?
o What is virtual inheritance?
o What is placement
new?
o What is the difference between
operator new
and the
new
operator?
¡¤ What is exception handling?
o Explain what happens when an
exception is thrown in C++.
o What happens if an exception is
not caught?
o What happens if an exception is
throws from an object's constructor?
o What happens if an exception is
throws from an object's destructor?
o What are the costs and benefits of
using exceptions?
o When would you choose to return an
error code rather than throw an exception?
¡¤ What is a template?
¡¤ What is partial specialization or template
specialization?
¡¤ How can you force instantiation of a template?
¡¤ What is an iterator?
¡¤ What is an algorithm (in terms of the STL/C++ standard
library)?
¡¤ What is
std::auto_ptr?
¡¤ What is wrong with this statement?
std::auto_ptr ptr(new char[10]);
¡¤ It is possible to build a C++ compiler on top of a C
compiler. How would you do this?

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:
2. class test
3. {
4. int x,y;
5. public:
6. test()
7. {
8. x=0; y=0;
9. }
10. void mod()
11. {
12. x=10;
13. y=15;
14. }
15. };
16. 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
17. 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.
18. 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.
19. 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.
20. What is the use of ¡®using¡‾ declaration.
A using declaration makes it possible to use a name from a namespace without
the scope operator.
21. 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.
22. 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.
23. 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).
24. 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.
25. int *i=0x400 // i points to address 400
26. *i=0; //set the value of memory location pointed
by i.
Incomplete types are otherwise called uninitialized pointers.
27. 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:
28. class Sample
29. {
30. public:
31. int *ptr;
32. Sample(int i)
33. {
34. ptr = new int(i);
}

~Sample()
{
delete ptr;
}
void PrintVal()
{
cout << ¡°The value is ¡± << *ptr;
}
};

void SomeFunc(Sample x)
{
cout << ¡°Say i am in someFunc ¡± << endl;
}

int main()
{
Sample s1 = 10;
SomeFunc(s1);
s1.PrintVal();
}

In the above example when PrintVal() function is


called it is called by the pointer that has been freed by the
destructor in SomeFunc.
35. Differentiate between the message and method.
Message:
o Objects communicate by sending messages to each other.
o A message is sent to invoke a method.
Method
o Provides response to a message.
o It is an implementation of an operation.
36. 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.
37. 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.
38. 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.
39. 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.
40. 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.
41. What are the conditions that have to be met for a condition to be an
invariant of the class?
o The condition should hold at the end of every constructor.
o The condition should hold at the end of every mutator (non-const)
operation.
42. What are proxy objects? Objects that stand for other objects are called
proxy objects or surrogates.
43. template <class t="">
44. class Array2D
45. {
46. public:
47. class Array1D
48. {
49. public:
50. T& operator[] (int index);
51. const T& operator[] (int index)const;
};

Array1D operator[] (int index);


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

The following then becomes legal:


Array2D<float>data(10,20);
cout<<data[3][6]; // fine
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.
52. Name some pure object oriented languages. Smalltalk, Java, Eiffel,
Sather.
53. Name the operators that cannot be overloaded. sizeof, ., .*, .->, ::, ?
: Salam in the comments notes that -> can be overloaded.
54. What is a node class? A node class is a class that,
o relies on the base class for services and implementation,
o provides a wider interface to the users than its base class,
o relies primarily on virtual functions in its public interface
o depends on all its direct and indirect base class
o can be understood only in the context of the base class
o can be used as base for further derivation
o 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.
55. 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.
56. 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.

Vous aimerez peut-être aussi