Friday, October 15, 2010
Puzzle
Write a function that adds two numbers. You should not use + or any arithmetic operators.
Lets have two number which are fairly large and try to add those two numbers but try a different approach.
987+789 = 1776
Lets just think backwards
987
+ 789
--------
666
Carry : 1110. This is calculated when the first carry is the first digit and the last carry is the last.
Add 1110 and 666 which gives you the ultimate result.
Now lets implement it in source (I am using python)
>>> def sum_without_arithmetic(a,b):
... if b==0:
... return a
... sum = a^b
... carry = (a&b)<<1
... return sum_without_arithmetic(sum, carry)
...
>>> sum_without_arithmetic(987,789)
1776
Thursday, October 14, 2010
More Interview Questions
Explain what happens, step by step, after you type a URL into a browser. Use as much details as possible.
1. Browser contacts the DNS server to find the IP address of the URL.
2. DNS server returns the IP address of the site.
3. Browser opens a TCP connection to the web server at port 80.
4. Browser fetches the html code of the page requested.
5. Browser renders the HTML in the display window.
6. Browser terminates the connection when window is closed.
Database:
1. What are different types of join? Please explain how they differ and why certain types are better in certain conditions.
JOIN is used to combine the results of two tables. To perform a join, each of the tables must have at least one field which will be used to find matching records from the other table. The join type defines which records will go into the result set.
1. INNER JOIN:
Result set will contain only those data where the criteria match.
2. OUTER JOIN:
Outer join will always contain the results of INNER JOIN, however it can contain some records that have no matching record in other table. OUTER JOINs are divided into following subtypes
2.1 LEFT OUTER JOIN or simply LEFT JOIN:
The result set will contain all the records from the left table. If no matching records were found in the right table, then its fields will contain NULL values.
2.2 RIGHT OUTER JOIN or simply RIGHT JOIN:
Opposite of the LEFT JOIN. It will contain all the records from the right table, and missing fields from the left table will contain NULL.
If we have two tables A and B, then we can say that statement A LEFT JOIN B is equivalent to statement B RIGHT JOIN A.
2.3 FULL OUTER JOIN
FULL OUTER JOIN combines the results of LEFT and RIGHT joins. All records from both the tables will be part of the result set, whether matching records exists in other table or not. If no matching record was found, then the corresponding result fields will have a NULL value.
C++
Compare and contrast Hash Table vs. STL map.
Hash Table:
In a hash table, a value is stored by applying hash function on a key. Thus, values are not stored in a hash table in sorted order. Additionally, since hash tables use the key to find the index that will store the value, an insert/lookup can be done in amortised O(1) time (assuming a few collisions in a hash table). One must also handle potential collisions in a hash table.
STL Map
In STL Map, insertion of key/value pair is in sorted order of key. It uses a treee to store values, which is why an O(log n) insert/lookup is required. There is also no need to handle collisions. An STL map works well for things like:
- find min element
- find max element
- print elements in a sorted order
- find the exact element or if the element is not found, find the next smallest number.
- A good hash function is required (e.g. operation % prime number) to ensure that the hash values are uni-formally distributed.
- A collision resolving method is also needed: chaining (good for dense table entries), probing (good for sparse table entries), etc.
- Implement methods to dynamically increase or decrease the hash table size on a given criterion. For example, when the [number of elements] by [table size] ratio is greater than the fixed threshold, increase the hash table size by creating a new hash table and transfer the entries from the old table to the new table by computing the index using new hash function.
You can use an STL map. Although this takes O(log n) time, since the number of inputs is small, this time is negligible.
Wednesday, May 5, 2010
C++ style puzzles
1. Given a vector
void f(vector
v[0]; // A
v.at(0); // B
}
If v is not empty then there is no difference between lines A and B. If v is empty, then line B is
guaranteed to throw a std::out_of_range exception, but there's no telling what line A might do.
There are two ways to access contained elements within a vector. The first, vector
Friday, August 21, 2009
Python Interview questions
1. What is list comprehension?
2. what is better += or .join()?
3. Do you know what is ISAPI filters?
4. How do you do unit testing?
5. What are you good with? Object oriented or subject oriented?
6. What is your favorite programming language? C++ or Python or anything else?
7. What is your favorite design pattern?
8. Explain singleton design pattern.
9. What version of Python do you use? 2.4/2.6/3.0?
10.Have you used any of the python frameworks? Django?
11. Are you are back end developer or a front end too?
12. When and why did you use Inno setup?
13. Explain difference between public, private and protected in C++
14. How many million pois we have in our db?
15. What is the percentage of C++ coding v/s Python coding in the last two years..?
16. Do you use Navteq maps for the map data?
17.
Thursday, June 4, 2009
C++ -- STL -- Vector -- Tutorial
Found out some good tutorial about Vectors. I believe most of the novice C++ programmers will know a lot about STL and vectors but this is one in case if somebody needs to brush up.
Vector Tutorial - Part I
Vector Tutorial - Part II
Hope this helps
Monday, May 11, 2009
Python Interview Questions and Answers
Hi Everybody,
As always interview questions but this time I was lucky to be interviewed for Python, which I had recent experience on. And the interviewer was great. He told me that he had pretty much fundamental and short questions to ask and he joked about MS interviewees will be joyed with this kind of interview process.
This was basically a python position but this made me feel why people cannot do with other programming language experts for python because a python programmer is really way too different than a C++ or Java programmer. Since I am a C++ programmer with recent experience in Python, I was considered for the position. It was fun going through the interview since it was web conference coding interview.
What I had gone through was the LinuxCBT edition of python which helped me a lot. If I had not referred that I would have done miserably.
I had tried searching for python questions over the internet but was not too lucky since I got only a few of them which made sense. Some of them were asked but restricting to just a couple of them. So I think my questions and answers will really help people to get a good idea on what can be asked for python interviews and also for people who are getting interviewed on python. I really appreciate comments and improvements on the questions and answers.
Hope the information helps.....
1. Name five modules that are included in python by default
2. Name a module that is not included in python by default
3. What is __init__.py used for?
4. When is pass used for?
5. What is a docstring?
6. What is list comprehension?
7. What is map?
8. What is the difference between a tuple and a list?
Ans. This is the most frequently asked question on python.
A tuple is a list that is immutable. A list is mutable i.e. The members can be changed and altered but a tuple is immutable i.e. the members cannot be changed.
Other significant difference is of the syntax. A list is defined as
list1 = [1,2,5,8,5,3,]
list2 = ["Sachin", "Ramesh", "Tendulkar"]
A tuple is defined in the following way
tup1 = (1,4,2,4,6,7,8)
tup2 = ("Sachin","Ramesh", "Tendulkar")
So the difference is in the type of brackets.
Coding questions
9. Using various python modules convert the list a to generate the output 'one, two, three'
a = ['one', 'two', 'three']
ANSWER:
>>> a = ['one','two','three']
>>> ','.join(a)
'one,two,three'
10. What would the following code yield?
word = 'abcdefghij' print word[:3] + word[3:]
Ans. This will print the word 'abcdefghij'
11. Optimize these statements as a python programmer
word = 'word'
print word.__len__()
ANSWER:
>>> print 'word'.__len__()
4
12. Write a program to print all the contents of a file
Ans.
try: f1=open("filename.txt","r") except Exception, e: print "%s" %e print f1.readlines()
ANSWER2:
with open("tmp1.txt", "r") as f: f.readlines()
13. What will be the output of the following code
a = 1
a,b=a+1,a+1
print a
print b
Ans.
2
2
Here in the second line a,b=a+1,a+1 means that a=a+1 and b=a+1 which is 2. But this is the python way of initialization which a python programmer should understand.
14. Given the list below remove the repetition of an element. All the elements should be uniquewords = ['one', 'one', 'two', 'three', 'three', 'two']
ANSWER:
>>> set(uniquewords)
set(['three', 'two', 'one'])
15. Iterate over a list of words and use a dictionary to keep track of the frequency(count) of each word. for example
{'one':2,'two':2,'three':2}
ANSWER:
>>> l = ['one', 'one', 'two', 'three', 'three', 'two', 'one', 'one', 'two']
>>> d = {}
>>> for w in l:
... d[w] = 1 + d.get(w,0)
...
>>> d
{'three': 2, 'two': 3, 'one': 4}
16.Write the following logic in Python:
If a list of words is empty, then let the user know it's empty, otherwise let the user know it's not empty.
Ans.
a=[]
if len(a):
print"The list is not empty"
else:
print"The list is empty"
17. Demonstrate the use of exception handling in python.
Ans.
a=[1,2,3,4]
try:
print a[5]
except Exception, e # This was important. Just do not say except: and print out something. It is
print e # Important to know what is the error
>>> a=[1,2,3,4]
>>> try:
... print a[5]
... except Exception, e:
... print "Error %s" % e
...
Error list index out of range
18. Print the length of each line in the file 'file.txt' not including any whitespaces at the end of the lines.
Ans.
>>> f1 = open("abc.py", 'r')
>>> i=0
>>> for line in iter(f1):
... print "Length of line %d is %d" % (i, len(line.rstrip()))
... i+=1
...
Length of line 0 is 11
Length of line 1 is 21
19. Print the sum of digits of numbers starting from 1 to 100
Ans. print sum(range(1,101))
This is way too easy but just who know python. Since I am a C++ Programmer, I started writing a for loop to add up which was way too dumb. Hope you don't make this mistake.
Python is known for it short syntax and easy to use functions.
20. Create a new list that converts the following list of number strings to a list of numbers.
num_strings = ['1','21','53','84','50','66','7','38','9']
Ans.
>>>num_strings = ['1','21','53','84','50','66','7','38','9']
>>>[int(j) for j in num_strings]
[1, 21, 53, 84, 50, 66, 7, 38, 9]
21. Create two new lists one with odd numbers and other with even numbers
num_strings = [1,21,53,84,50,66,7,38,9]
Ans. >>>num_strings = [1,21,53,84,50,66,7,38,9] >>>o, e = [], [] >>>[o.append(n) if n % 2 else e.append(n) for n in num_strings] [None, None, None, None, None, None, None, None, None] >>>o,e ([1, 21, 53, 7, 9], [84, 50, 66, 38])
>>> num_strings = [1,21,53,84,50,66,7,38,9]
>>> odd, even = filter(lambda x:x%2, num_strings), filter(lambda x: not x%2, num_strings)
>>> print odd,even
[1, 21, 53, 7, 9] [84, 50, 66, 38]
22. Write a program to sort the following intergers in list
nums = [1,5,2,10,3,45,23,1,4,7,9]
nums.sort() # This is the quickest sorting algorithm. This is the best possible way to sort.
print nums
23. Write a for loop that prints all elements of a list and their position in the list.
abc = [4,7,3,2,5,9]
Ans.
>>>abc = [4,7,3,2,5,9] >>>for i, v in enumerate(abc): ... print i,v ... 0 4 1 7 2 3 3 2 4 5 5 9
24. The following code is supposed to remove numbers less than 5 from list n, but there is a bug. Fix the bug.
n = [1,2,5,10,3,100,9,24] for e in n: if e<5: n.remove(e) print n
Ans. The output here will be
[2,3,5,10,100,9,24] which means the 1st and the 5th elements are removed.
It should be implemented as below.
>>> n = [1,2,5,10,3,100,9,24]
>>> nlist = filter(lambda x: x >= 5, n)
>>> print nlist
[5, 10, 100, 9, 24]
list.remove(element) will remove the element, and shrink the list. If
you are iterating over the same list at that time, and you wanted to
go to next element, the next element may very well be the one after.
Here is what is happening in the problem: The 0th element in the list
is less than 5 and is removed, thus, making the list shorter by one
element. The next iteration in the for loop goes to n[1], but n[0]
now is 2, so the loop skips element 2 and doesn't remove it. Same
thing happens at 100, but it is ok to skip 100 as it is > 5
25. What will be the output of the following
def func(x,*y,**z): print z func(1,2,3)
Ans.
Here the output is :
{}
If I print all the variables, namely x, y and z it yeilds me this
1 (2,3) {}
* and ** have special usage in the function argument list. *
implies that the argument is a list and ** implies that the argument
is a dictionary. This allows functions to take arbitrary number of
arguments (like your sum function that took range of numbers from 0
.. 100. Pretty cool, eh?
26. Write a program to swap two numbers.
a = 5 b = 9 def swap(c,d): return d,c swap(a,b)
This will print the swapped values of a and b
(9,5)
OR if this does not seem convincing,
a, b = 5, 10 t = a a=b b=t print a,b
>>> a = 5
>>> b = 10
>>> a,b=b,a
>>> a
10
>>> b
5
27. What will be the output of the following code
class C(object): def__init__(self): self.x =1 c=C() print c.x print c.x print c.x print c.x
Ans.
All the outputs will be 1
1
1
1
1
28. What is wrong with the code
func([1,2,3]) # explicitly passing in a list func() # using a default empty list def func(n = []): #do something with n print n
Ans. I tried running the code with my addition of printing the value of n in the function and found out the following result
func([1,2,3]) resulted in [1,2,3]
while func() resulted in []
29. What all options will work?
a.
n = 1
print n++
b.
n = 1
print ++n
c.
n = 1
print n+=1
d.
int n = 1
print n = n+1
e.
n =1
n = n+1
From the above options I believe the following will work
b. and e.
There are some problems with a, c and d.
if you try running the code in a , it does not accept n++ but it accepts ++n
n+=1 is not accepted while in d the variable is preceded by an int which is not pythonically correct.
30. In Python function parameters are passed by value or by reference?
Ans. Please refer to this
31.Remove the whitespaces from the string.
s = 'aaa bbb ccc ddd eee'
Ans.
a = string.split(s)
print a
['aaa', 'bbb', 'ccc', 'ddd', 'eee'] # This is the output of print a
print string.join(a)
aaa bbb ccc ddd eee # This is the output of print string.join(a)
32. What does the below mean?
s = a + '[' + b + ':' + c + ']'
33. Optimize the below code
def append_s(words):
new_words=[]
for word in words:
new_words.append(word + 's')
return new_words
for word in append_s(['a','b','c']):
print word
The above code adds a trailing s after each element of the list. Is there a better way one can write the above script?
34. If given the first and last names of bunch of employees how would you store it and what datatype?
Ans. Either a dictionary or just a list with first and last names included in an element.
35.
36.
Tuesday, April 14, 2009
New C++ questions....
Surprisingly the number of interview questions posts have increased since I am appearing for a number of interviews..... but surely this helps me and I hope that it will help some other people too.
1. Tell me the fundamentals of OOPS.
--> Encapsulation, Inheritance, Polymorphism. Define them.
Surprisingly I was asked that I missed abstraction. I believe it is a generic term for encapsulation.
2. Implementation of polymorphism in recent projects...
Implemented the Logger class to log all the install scripts as well as other database related scripts.
3. What kind of polymorphism did you implement in the recent projects?
--> Run time polymorphism.
4. Explain operator overloading.
5. What is a virtual funtion?
6. What are memory leaks?
7. What is a function pointer?
8. What is a VPT (Virtual Pointer Table)?
--> The virtual table is actually quite simple, though it’s a little complex to describe in words. First, every class that uses virtual functions (or is derived from a class that uses virtual functions) is given it’s own virtual table. This table is simply a static array that the compiler sets up at compile time. A virtual table contains one entry for each virtual function that can be called by objects of the class. Each entry in this table is simply a function pointer that points to the most-derived function accessible by that class.
9. What is a smart pointer?
-->Smart pointers are objects which store pointers to dynamically allocated (heap) objects. They behave much like built-in C++ pointers except that they automatically delete the object pointed to at the appropriate time. Smart pointers are particularly useful in the face of exceptions as they ensure proper destruction of dynamically allocated objects. They can also be used to keep track of dynamically allocated objects shared by multiple owners.
Friday, April 3, 2009
C++/Perl/Bash/Python questions
1. What is the difference between Bash/Shell, perl, python scripting languages?
--> Perl and Python can be used for web based scripting while bash cannot be used.
--> Easy portability for perl and python since both are platform independent while bash is not.
--> Various flavors of shell scripting, bash, korn, ksh, etc.
2. Why is a virtual constructor not possible?
A constructor cannot be virtual because at the time when the constructor is invoked, the virtual table would not be available in the memory. Hence we cannot have a virtual constructor.
3. Can we have an array of references?
No we cannot have an array of references because references cannot be null as pointers can be. Once a reference is created, it cannot be later made to reference another object. We can say it cannot be reseated which is often done with pointers.
References cannot also be uninitialized.
4. Describe the callback function syntax.
5. What is the difference between exec() and system() in perl/bash?
exec() executes in the same shell while system() executes in another shell.
6. Define a constructor and how it might be called.
Constructor is a member function of the class, with the name of the function being the same as the class name. It also specifies how the object should be initialized.
There are two ways of calling a constructor
1. Implicitly - automatically by compiler when an object is created.
2. Explicitly - Calling the constructors explicitly is possible but it makes code unverifiable.
class Point
{
int x,y;
public:
Point():x(0),y(0) {} // Default constructor with no arguments
};
void main()
{
Point MyPoint; // Implicit constructor call. In order to allocate memory on stack, the default constructor is implicitly called.
Point *pPoint = new Point(); //Explicit constructor call. In order to allocate memory on heap we call the default constructor.
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;
}
};
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
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
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.
What is a const method?
Marking a method as const signs a contract with the client code guaranteeing that you will not try to change the internal values of the object within the method.
If you try to declare a method const that actually modifies a data member, the compiler will complain.
You cannot declare a static method const because it is redundant.
Static methods do not have an instance of the class so it would be impossible for them to change internal values.
const works by making it appear inside the method that you have a const reference to each data member. Thus, if you try to change the data member the compiler will flag an error.
A non-const object can call const and no-const methods. However, a const object can only call const methods. Note that const objects can still be destroyed, and their destructor can be called. You shouldn't try to mark the destructor const.
Syntax of a const method:
double SpreadSheetCell::getValue() const
{
}
string SpreadSheetCell::getString() const
{
}
One should not get into the habit of declaring const all methods that don't modify the object so that you can use references to const objects in your program.
Saturday, March 21, 2009
Fundamental questions of C++
The following are the initial questions asked by a technical recruiter for a good project in C++. Have a look and hope this helps.
What is the difference between an ARRAY and a LIST?
-->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.
-->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 the word you will use when defining a function in base class to allow this function to be a polimorphic function?
-->Virtual
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
What is the difference between Mutex and Binary semaphore?
semaphore is used to synchronize processes. where as mutex is used to provide synchronization between threads running in the same process.
STL Containers - What are the types of STL containers?
There are 3 types of STL containers:
1. Adaptive containers like queue, stack
2. Associative containers like set, map
3. Sequence containers like vector, deque
Describe two ways where you can prevent a class from being instantiated.
--> Declare all static methods/functions.
--> Declare a private constructor.
Difference between DELETE, TRUNCATE and DROP statements in SQL
--> DELETE
- DML statement
- used to remove rows from a table
- WHERE clause can be sued to remove only some rows.
- After performing DELETE operation you can commit or rollback the transaction to make the change permenant or undo it.
- This operation will cause all TRIGGERS on table to fire.
--> TRUNCATE
- DDL statement
- removes all rows from a table
- operation cannot be rolled back and no triggers will be fired.
- TRUNCATE is faster and doesn't use as much undo space as DELETE.
--> DROP
- DDL statement
- removes a table from a database
- all the tables' rows, indexes and privileges will also be removed.
- No DML triggers will be fired.
- Operation cannot be rolled back.
From Oracle 10g a table can be undropped.
FLASHBACK TABLE emp TO BEFORE DROP
Flashback Complete
Thursday, March 19, 2009
XML -- Interview Questions
Interview preparation can be a difficult process and in the current market scenario one has to have the right skills and capabilities to get a job.
So I have a bunch of stuff that I have hands on experience but do not have thorough knowledge of. Lets begin with XML today.
1. What is XML?
Ans. XML (eXtensible Markup Language) is all about describing data.
2. What are the namespaces in .NET used for XML?
Ans.
1. System.Xml
2. System.Xml.Schema
3. System.XML.XPath
4. System.Xml.Xsl
3. What is a XML Parser?
Ans. XML Parser sits in between the XML document and the application who wants to use the XML document.
There are two standard specifications which are very common and should be followed by a XML parser:-
DOM (Document Object Model)
- W3C recommended way for treating XML documents.
- Load entire XML document into memory and allows us to manipulate the structure and data of XML document.
SAX (Simple API for XML
- Event Driven way for processing XML documents.
- SAX parser parses XML document sequentially and emits events like start and end of the document, elements, text content, etc.
- Best for large XML documents which cannot be loaded directly into the memory.
4. What are the core functionalities in XML.NET framework?
Ans. The core functionalities in XML.NET framework are
1. XML Readers
2. XML Writers
3. XML Document
1. XML Readers
- allows you to scroll forward through the contents like moving from node to node or element to element.
- allows you to browse through the XML document.
2. XML Writers
- can store the XML contents to any other storage media.
3. XML Document
- provides a in memory representation for the data in an XMLDOM structure as defined by W3C.
- supports browsing and editing of the document.
- Gives complete tree structure representation of your XML document.
5. What is XSLT?
- rule based language used to transform XML docs into other file formats.
- generic transformation rules which can be applied to transform XML document to HTML, CSS, Rich Text, etc.
6. What is XPATH?
- XML query language to select specific parts of an XML document.
- Using XPATH you can address or filter elements and text in a XML document.
- e.g. "Invoice/Amount" states find "Amount" node which are children of "Invoice" node.
7. What is a XPointer?
- used to locate data within XML document.
- can point to a particular portion of XML document.
- e.g.
address.xml#xpointer(/descendent::streetnumber[@id=9])
- So the above XPOINTER points streetnumber = 9 in "address.xml".
8. What is a XMLReader Class?
- abstract class from System.XML namespace.
- works on a read only stream browsing from one node to another in forward direction.
- You cannot modify the XML document. You can only move forward.
9. What is a XMLTextReader?
- helps provide fast access to streams of XML data in a fowrward-only and read-only manner.
- checks if the XML is well formed (properly formatted with opening and ending tags)
- does not validate against a schema or DTD for that you will need "XmlNodeReader" or "XmlValidationReader" class.
Tuesday, February 3, 2009
C++ Interview questions
These days I am giving interviews in my field of expertise i.e. C++. Well am not expert but that is what I am looking for in terms of technology.
Ok so getting to the point, I found it useful for myself as well as other to ponder into some of the latest questions that were asked by an interviewer in India... no wonder india is the software hub.
The answers are according to my knowledge. Do comment on it and correct me wherever I am wrong.
1. What are different kinds of design patterns?
i Singleton
ii Factory
iii Proxy
iv Adapter/Wrapper
v Decorator
vi The chain of responsibility
vii Observer Pattern
2. How would you implement a Singleton Application?
Implementing the Singleton Design Pattern
By Danny Kalev
Singleton is probably the most widely used design pattern. Its intent is to ensure that a class has only one instance, and to provide a global point of access to it. There are many situations in which a singleton object is necessary: a GUI application must have a single mouse, an active modem needs one and only one telephone line, an operating system can only have one window manager, and a PC is connected to a single keyboard. I will show how to implement the singleton pattern in C++ and explain how you can optimize its design for single-threaded applications.
Design Considerations
Using a global object ensures that the instance is easily accessible but it doesn't keep you from instantiating multiple objects—you can still create a local instance of the same class in addition to the global one. The Singleton pattern provides an elegant solution to this problem by making the class itself responsible for managing its sole instance. The sole instance is an ordinary object of its class, but that class is written so that only one instance can ever be created. This way, you guarantee that no other instance can be created. Furthermore, you provide a global point of access to that instance. The Singleton class hides the operation that creates the instance behind a static member function. This member function, traditionally called Instance(), returns a pointer to the sole instance. Here's a declaration of such a class:
class Singleton
{
public:
static Singleton* Instance();
protected:
Singleton();
Singleton(const Singleton&);
Singleton& operator= (const Singleton&);
private:
static Singleton* pinstance;
};
Instead of Singleton, you can name your class Mouse, FileManager, Scheduler, etc., and declare additional members accordingly. To ensure that users can't create local instances of the class, Singleton's constructor, assignment operator, and copy constructor are declared protected. The class also declares a private static pointer to its instance, pinstance. When the static function Instance() is called for the first time, it creates the sole instance, assigns its address to pinstance, and returns that address. In every subsequent invocation, Instance() will merely return that address.
The class's implementation looks like this:
Singleton* Singleton::pinstance = 0;// initialize pointer
Singleton* Singleton::Instance ()
{
if (pinstance == 0) // is it the first call?
{
pinstance = new Singleton; // create sole instance
}
return pinstance; // address of sole instance
}
Singleton::Singleton()
{
//... perform necessary instance initializations
}
Users access the sole instance through the Instance() member function exclusively. Any attempt to create an instance not through this function will fail because the class's constructor is protected. Instance() uses lazy initialization. This means the value it returns is created when the function is accessed for the first time. Note that this design is bullet-proof—all the following Instance() calls return a pointer to the same instance:
Singleton *p1 = Singleton::Instance();
Singleton *p2 = p1->Instance();
Singleton & ref = * Singleton::Instance();
Although our example uses a single instance, with minor modifications to the function Instance(), this design pattern permits a variable number of instances. For example, you can design a class that allows up to five instances.
Optimizing Singleton for Single-Threaded Applications
Singleton allocates its sole instance on the free-store using operator new. Because operator new is thread-safe, you can use this design pattern in multi-threaded applications. However, there's a fly in the ointment: you must destroy the instance manually by calling delete before the application terminates. Otherwise, not only are you causing a memory leak, but you also bring about undefined behavior because Singleton's destructor will never get called. Single-threaded applications can easily avoid this hassle by using a local static instance instead of a dynamically allocated one. Here's a slightly different implementation of Instance() that's suitable for single-threaded applications:
Singleton* Singleton::Instance ()
{
static Singleton inst;
return &inst;
}
The local static object inst is constructed when Instance() is called for the first time and remains alive until the application terminates. Note that the pointer pinstance is now redundant and can be removed from the class's declaration. Unlike dynamically allocated objects, static objects are destroyed automatically when the application terminates, so you shouldn't destroy the instance manually.
3. What if you do not want to permit instantiation of a class?
A class type should be declared abstract only if the intent is that subclasses can be created to complete the implementation. If the intent is simply to prevent instantiation of a class, the proper way to express this is to declare a constructor (§8.8.8) of no arguments, make it private, never invoke it, and declare no other constructors. A class of this form usually contains class methods and variables. The class Math is an example of a class that cannot be instantiated; its declaration looks like this:
public final class Math {
private Math() { } // never instantiate this class
. . . declarations of class variables and methods . . .
}
Ans 2
Make it a pure virtual class. That means no implementation of any functions in the class.
4. If you do not have to use namespaces, and have two third party Libraries with the same header file name?
5. What all things would you consider while considering addition of a third party library?
6. What is a select class in socket programming?
7. What are the different Synchronization objects?
i Classic Semaphores
ii Mutex
iii Event Objects
iv Waitable timers
v Critical section Object
8. How would you handle a file that is to be accessed by three different threads?
9. What are the steps that are involved in accessing a resource with the involvement of synchronization objects?
10.What is the library you use to open and close a file?
Stream
Step 1: Creating a File Stream
An input file stream (ifstream) supports the overloaded >> operator. Likewise, an output file stream (ofstream) supports the << operator. A file stream that combines both input and output is called fstream. The following program creates an ifstream object called dictionary and prints each word in it on the screen:
#include
#include
#include
#include
using namespace std;
int main()
{
string s;
cout<<"enter dictionary file: ";
cin>>s;
ifstream dictionary (s.c_str());
if (!dictionary) // were there any errors on opening?
exit(-1);
while (dictionary >> s) cout << s <<'\n';
}
We have to call the string::c_str() member function because fstream objects accept only const char * filenames. When you pass a filename as an argument, the constructor attempts to open the specified file. Next, we use the overloaded ! operator to check the file's status. If an error has occurred, the operator will evaluate as true. The last line contains a loop that, on each iteration, reads a word from the file, copies it to s and displays it. Note that we didn't have to check for an EOF character explicitly as the overloaded >> handles this condition automatically. Furthermore, we didn't close the file explicitly because the destructor does that for us.
11. Tell me something about virtual constructors and destructors.
Constructor cannot be virtual because at the time when the constructor is invoked, the virtual table would not be available in the memory. Hence we cannot have a virtual constructor
Virtual Destructor
- A virtual destructor is one that is declared as virtual in the base class and is used to ensure that destructors are called in proper order.
- It is to be remembered that destructors are called in reverse order of inheritance
- If a base class pointer points to a derived class object and we sometime later use the delete operator to delete the object, then the derived class destructor is not called.
- But if the keyword virtual is used while the destructor is declared in base class, ,in the above case, the derived class destructor is called.
Pure Virtual Destructor
- We cannot declare a pure virtual destructor. Even if a virtual destructor is declared as pure, it will have to implement an empty body(at least) for the destructor.