Tuesday, October 23, 2007

C++ notes

1. What is the output of printf(“%d”)?

1. %d helps to read integer data type of a given variable
2. when we write (“%d”, X) compiler will print the value of x assumed in the main
3. but nothing after (“%d”) so the output will be garbage
4. printf is an overload function doesnt check consistency of the arg list – segmentation fault


2. What will happen if I say delete this? - destructor executed, but memory will not be freed (other than work done by destructor). If we have class Test and method Destroy { delete this } the destructor for Test will execute, if we have Test *var = new Test()

1. pointer var will still be valid
2. object created by new exists until explicitly destroyed by delete
3. space it occupied can be reused by new
4. delete may only be applied to a pointer by new or zero, applying delete to zero = no FX
5. delete = delete objects
6. delete[] – delete array
7. delete operator destroys the object created with new by deallocating the memory assoc. with the object
8. if a destructor has been defined fir a class delete invokes that desructor


3. Difference between C structure and C++ structure - C++ places greater emphasis on type checking, compiler can diagnose every diff between C and C++

1. structures are a way of storing many different values in variables of potentially diff types under under the same name
2. classes and structures make program modular, easier to modify make things compact
3. useful when a lot of data needs to be grouped together
4. struct Tag {…}struct example {Int x;}example ex; ex.x = 33; //accessing variable of structure
5. members of a struct in C are by default public, in C++ private
6. unions like structs except they share memory – allocates largest data type in memory - like a giant storage: store one small OR one large but never both @ the same time
7. pointers can point to struct:
8. C++ can use class instead of struct (almost the same thing) - difference: C++ classes can include functions as members
9. members can be declared as: private: members of a class are accessible only from other members of their same class; protected: members are accessible from members of their same class and friend classes and also members of their derived classes; public: members are accessible from anywhere the class is visible
10. structs usually used for data only structures, classes for classes that have procedures and member functions
11. use private because in large projects important that values not be modified in an unexpected way from the POV of the object
12. advantage of class declare several diff objects from it, each object of Rect has its own variable x, y AND its own functions
13. concept of OO programming: data and functions are properties of the object instead of the usual view of objects as function parameters in structured programming


4. Difference between assignment operator and copy constructor

1. constructor with only one parameter of its same type that assigns to every nonstatic class member variable of the object a copy of the passed object
2. copy assignment operator must correctly deal with a well constructed object - but copy constructor initializes uninitialized memory
3. copy constructor takes care of initialization by an object of the same type x
4. for a class for which the copy assignment and copy constructor not explicitly declared missing operation will be generated by the compiler. Copy operations are not inherited - copy of a class object is a copy of each member
5. memberwise assignment: each member of the right hand object is assigned to the corresponding member of the left hand object
6. if a class needs a copy constructor it will also need an assignment operator
7. copy constructor creates a new object, assignment operator has to deal w/ existing data in the object
8. assignment is like deconstruction followed by construction
9. assignment operator assigns a value to a already existing object
10. copy constructor creates a new object by copying an existing one
11. copy constructor initializes a freshly created object using data from an existing one. It must allocate memory if necessary then copy the data
12. the assignment operator makes an already existing object into a copy of an existing one.
13. copy constructor always creates a new object, assignment never does


5. Difference between overloading and overriding?

1. Overload - two functions that appear in the same scope are overloaded if they have the same name but have different parameter list
2. main() cannot be overloaded
3. notational convenience - compiler invokes the functions that is the best match on the args – found by finding the best match between the type of arg expr and parameter
4. if declare a function locally, that function hides rather than overload the same function declared in an outer scope
5. Overriding - the ability of the inherited class rewriting the virtual method of a base class - a method which completely replaces base class FUNCTIONALITY in subclass
6. the overriding method in the subclass must have exactly the same signature as the function of the base class it is replacing - replacement of a method in a child class
7. writing a different body in a derived class for a function defined in a base class, ONLY if the function in the base class is virtual and ONLY if the function in the derived class has the same signature
8. all functions in the derived class hide the base class functions with the same name except in the case of a virtual functions which override the base class functions with the same signature


6. Virtual

1. single most important feature of C++ BUT virtual costs
2. allows derived classes to replace the implementation provided by the base class
3. without virtual functions C++ wouldnt be object oriented
4. Programming with classes but w/o dynamic binding == object based not OO
5. dynamic binding can improve reuse by letting old code call new code
6. functions defined as virtual are ones that the base expects its derived classes to redefine
7. virtual precedes return type of a function
8. virtual keyword appears only on the member function declaration inside the class
9. virtual keyword may not be used on a function definition that appears outside the class body
10. default member functions are nonvirtual


7. Dynamic Binding

1. delaying until runtime the selection of which function to run
2. refers to the runtime choice of which virtual function to run based on the underlying type of the object to which a reference or a pointer is based
3. applies only to functions declared as virtual when called thru reference or ptr
4. in C++ dynamic binding happens when a virtual function is called through a reference (|| ptr) to a base class. The face that ref or ptr might refer to either a base or a derived class object is the key to dynamic binding. Calls to virtual functions made thru a reference or ptr are resolved at run time: the function that is called is the one defined by the actual type of the object to which the reference or pointer refers


8. Explain the need for a virtual destructor

1. destructor for the base parts are invoked automatically
2. we might delete a ptr to the base type that actually points to a derived object
3. if we delete a ptr to base then the base class destructor is run and the members of the base class are cleared up. If the objectis a derived type then the behavior is undefined
4. to ensure that the proper destructor is run the destructor must be virtual in the base class
5. virtual destructor needed if base pointer that points to a derived object is ever deleted (even if it doesnt do any work)


9. Rule of 3

1. if a class needs a destructor, it will also need an assignment operator and copy constructor
2. compiler always synthesizes a destructor for us
3. destroys each nonstatic member in the reverse order from that in which the object was created
4. it destroys the members in reverse order from which they are declared in the class1. if someone will derive from your class2. and if someone will say new derived where derived is derived from your class3. and if someone will say delete p, where the actual objects type is derived but the pointer ps type is your class
5. make destructor virtual if your class has any virtual functions


10. Why do you need a virtual destructor when someone says delete using a Base ptr thats pointing to a derived object?

When you say delete p and the class of p has a virtual destructor the destructor that gets invoked is the one assoc with the type of the object*p not necessarily the one assoc with the type of the pointer == GOOD


11. Different types of polymorphism

1. types related by inheritance as polymorphic types because we can use many forms of a derived or base type interchangeably
2. only applies to ref or ptr to types related by inheritance.
3. Inheritance - lets us define classes that model relationships among types, sharing what is common and specializing only that which is inherently different
4. derived classes
   a. can use w/o change those operations that dont depend on the specifics of the derived type
   b. redefine those member functions that do depend on its type
   c. derived class may define additional members beyond those it inherits from its base class.
5. Dynamic Binding - lets us write programs that use objects of any type in an inheritance hierarchy w/o caring about the objects specific types
6. happens when a virtual function is called through a reference || ptr to a base class
7. The fact that a reference or ptr might refer to either a base or derived class object is the key to dynamic binding
8. calls to virtual functions made though a reference/ptr resolved @ runtime
9. the function that is called is the one defined by the actual type of the object to which ref/ptr refers


12. How to implement virtual functions in C

Keep function pointers in function and use those function ptrs to perform the operation


13. What are the different type of Storage classes?

1. automatic storage: stack memory - static storage: for namespace scope objects and local statics
2. free store: or heap for dynamically allocated objects == design patterns


14. What is a namespace?
1. every name defined in a global scope must be unique w/in that scope
2. name collisions: same name used in our own code or code supplied to us by indie producers == namespace pollution
3. name clashing - namespace provides controlled mechanism for preventing name collisions
4. allows us to group a set of global classes/obj/funcs
5. in order to access variables from outside namespace have to use scope :: operator
6. using namespace serves to assoc the present nesting level with a certain namespace so that objectand funcs of that namespace can be accessible directly as if they were defined in the global scope


15. Types of STL containers

Containers are objects that store other objects and that has methods for accessing its elements - has iterator - vector


16. Difference between vector and array

array: data structure used dto store a group of objects of the same type sequentially in memory.

vector: container class from STL - holds objects of various types - resize, shrinks grows as elements added - bugs such as accessing out of bounds of an array are avoided


17. Write a program that will delete itself after execution.

Int main(int argc, char **argv) { remove(argv[0]);return 0;}


18. What are inline functions?

1. treated like macro definitions by C++ compiler
2. meant to be used if there’s a need to repetitively execute a small block if code which is smaller
3. always evaluates every argument once
4. defined in header file
5. avoids function call overload because calling a function is slower than evaluating the equivalent expression
6. it’s a request to the compiler, the compiler can ignore the request

19. What is strstream?

Defines classes that support iostreams, array of char obj


20. Passing by ptr/val/refArg?

1. passing by val/refvoid c::f(int arg) – by value arg is a new int existing only in function. Its initial value is copied from i. modifications to arg wont affect the I in the main function
2. void c::f(const int arg) – by value (i.e. copied) the const keyword means that arg cant be changed, but even if it could it wouldnt affect the I in the main function
3. void c::f(int& arg) - -by reference, arg is an alias for I. no copying is done. More efficient than methods that use copy. Change in arg == change in I in the calling function
4. void c::f(const int& arg) - -by reference, int provided in main call cant be changed, read only. Combines safety with efficacy.
5. void c::f(const int& arg) const – like previous but final const that in addition the function f cant change member variables of cArg passing using pointers
6. void c::f(int *arg) – by reference changing *arg will change the I in the calling function
7. void c::f(const int *arg) – by reference but this time the I int in the main function cant be changed – read only
8. void c::f(int * const arg) – by reference the pointer arg cant be changed but what it points to (namely I of the calling function) can
9. void c::f(const int * const arg) by reference the pointer arg cant be changed neither can what it points to


21. Mutable keyword?

1. keyword is the key to make exceptions to const
2. mutable data member is allowed to change during a const member function
3. mutable data member is never const even when it is a member of a const object
4. a const member function may change a mutable member


22. Difference between calloc and malloc?

1. malloc: allocate s bytes
2. calloc: allocate n times s bytes initialized to 0


23. Difference between printf and sprintf?

1. sprintf: a function that puts together a string, output goes to an array of char instead of stdout
2. printf: prints to stdout


24. map in STL?

1. used to store key - value pairs, value retrieved using the key
2. store data indexed by keys of any type desire instead of integers as with arrays
3. maps are fast 0(log(n)) insertion and lookup time
4. std::mapEX:Std::map grade_list //grade_list[“john”] = b


25. When will we use multiple inheritance?

1. use it judiciously class
2. when MI enters the design scope it becomes possible to inherit the same name (function/typedef) from more than one base class == ambiguity
3. C++ first identifies the function thats the best match for the call
4. C++ resolves calls to overload before accessibility, therefore the accessibility of Elec_Gadget() checkout is never evaluated because both are good matches == ERROR
5. resolve ambiguity mp.Borrowable_Item::checkOut(); mp.Elec_Gadget::checkOut(); //error because trying to access private
6. deadly MI diamond: anytime you have an inheritance hierarchy w/ more than one path between a base class and a derived classEX:FileInput File Output FileIOFile//File and IOFile both have paths through InputFile and OutputFile


26. Multithreading

C++ does not have a notion of multithreading, no notion of concurrency


27. Why is the pre-increment operator faster than the post-increment operator?
pre is more efficient that post because for post the object must increment itself and then return a temporary containing its old value. True for even built in types


Programming Ring - New Post
Programming Ring - Old Post

Wednesday, October 10, 2007

Founder of Arsenal FC

I am big fan of Arsenal FC since 1997 - the year they started showing EPL in India. My daily routine is to go online on google news and read stories/news about Arsenal. I came across a very interesting article about founder of arsenal.

Below is complete reproduction of article without any modification. All the thoughts/words are of the original writter. I have put a link for people interested in reading the original article.

***********************************************

LAST month, as Thierry Henry and his new Barcelona team-mates held court at St Andrews, down the road in Burntisland, with rather less fanfare, another seminal figure in the Arsenal story was being accorded an overdue and much deserved tribute.

The Frenchman may not be too familiar with the name of David Danskin but he, and every other player who has donned a Gunners shirt down the years, owes Danskin a debt of gratitude. The Fifer is the man who laid the foundations of the London club, 121 years ago, and the first in the line of a little-known football dynasty that continues to this day.

On July 23, with former Arsenal and Scotland keeper Bob Wilson in attendance, Danskin's role as Arsenal's founder was formally acknowledged with the unveiling of a commemorative plaque near the site of the tenement where he grew up.

Danskin was born in 1863, the son of an iron-turner. His family had moved down the coast from Kirkcaldy to Burntisland following the opening of the Edinburgh and Northern Railway in 1847, when the town had become a major ferry port and railway terminus.

Like Lanarkshire and Ayrshire, Fife was already a strong football hotbed, and the source of many talented players who would later move south. As a teenager, Danskin captained a Kirkcaldy Wanderers team that featured two other future Arsenal players, Peter Connolly and Jack McBean.

In 1883, aged 20, he gave up his engine fitter apprenticeship in Kirkcaldy and moved to Kent, where he had been offered a job at the Woolwich Arsenal munitions factory.

Association football was viewed by many with suspicion in the rugby-dominated south of England, but Danskin was a determined evangeliser for the round-ball game. After several failed attempts, in October 1886, he persuaded a group of like-minded colleagues to club together and buy a football. It was the first important step towards the formation of Dial Square, named after one of the workshops in the factory, and the earliest incarnation of the team that would eventually become Arsenal.

The club was officially formed on December 1, 1886 at meeting at the Royal Oak public house in Woolwich, with Danskin and his fellow members agreeing that it should be rechristened Royal Arsenal. Ten days later, with full-back Danskin named captain, the team played its first ever fixture on a bog of a pitch on the Isle of Dogs in London's East End, thrashing Eastern Wanderers 6-0. Lining up behind Danskin was fellow founder member, Fred Beardsley, who doubled up as keeper for Nottingham Forest. Beardsley had managed to borrow some old shirts from his other club, which is why, to this day, Arsenal, like Forest, play in red.

Danskin featured regularly for the next three years With the team still making its mark, there was no silverware, but he was part of the team that reached the semi-final of the London Association Senior Challenge Cup in 1889, losing to local rivals Clapton Wanderers.

Plagued by injuries, Danskin reluctantly decided to stop playing later that year. However, he made a one-off return to the team in March 1890 as makeshift goalkeeper, standing in for Beardsley, who was away playing for Nottingham Forest. His passion for the game did not wane, and he remained involved as a coach, and even occasional referee. In June 1892, by which point the club had changed its name to Woolwich Arsenal and turned professional, he was elected on to the club's committee.

According to the 1901 census, by the turn of the century Danskin was earning a living as a mechanical engineer, and had also started his own business - making and selling bicycles under the brand name Cushie-Doo - from above the family home in Plumstead, a stone's throw from Woolwich Arsenal. In 1907, after being offered a senior job with the Standard Motor Company, he sold up and moved the family to Coventry. In March 1916, Danskin's wife Georgina died of emphysema. He remarried two years later, to Rose Clara Richardson, and the couple had three children.

When Arsenal won the FA Cup in 1936, Danskin's employers threw a special celebration dinner in his honour. Danskin, though, was by now suffering serious problems with his legs - probably the result of old football injuries - and had been forced to listen to the live radio broadcast of the final from his sickbed.

Told he would need to have a leg amputated, he replied: "I've got two legs now and if I'm going to die, I'll die with two legs."

Eventually he had to be admitted as a hospital in-patient. He died in Warwick on August 4, 1948, at the age of 85, and is buried in Coventry. For the best part of half a century his story died with him.

It was largely down to the efforts of his grandson, Richard Wyatt, that his connection to Burntisland has been identified. Wyatt, who lives in Canada, made his first pilgrimage to the town several years ago, and has since collaborated closely with the Burntisland Trust to piece together his grandfather's story.

"The curiosity about my grandfather's life has always been there," he said in an interview during that visit in 2004.

"But without the internet there were few starting points for my research in Canada. I always wanted to make the trip to Burntisland and see where he was born.

"It's amazing to think of all the great players and managers Arsenal have produced over the years and know they are linked back to my grandfather and Burntisland."

There is another contemporary twist to the Danskin tale. Twelve decades on, the family tradition is being kept alive, down under, in the person of Danskin's great-great nephew, Matt, an Australian youth international who was once on the books of Werder Bremen.

Matt Danskin's father, Andrew, himself a footballer with Leeds United before emigrating to Australia in the 1970s, explained the thread that links his son to the Arsenal founder: "David Danskin had a younger brother called William, born in 1874. William's son John William was my grandfather. He had ten children, one of whom was my father, also John William.

John William's branch of the family moved to the north-east of England in search of work, before settling in Yorkshire, where they provided three generations of Leeds United players.

"My grandfather's brother, Bob Danskin, played for Leeds and Bradford Park Avenue in the late 1920s and 1930s. My father also went on to play for the Leeds reserve team," added Andrew Danskin.

"I also played for Leeds United from 1967 to 1970. So there is a great soccer tradition in the family, and now my son, Matt, is continuing it."

In 2001, Matt Danskin was spotted playing for Western Australia Under-16s by a scout from Werder Bremen and went on to play for the Bundesliga club's U19 team. After failing to break into the senior squad, he headed home in 2004, signing for Perth SC of the Western Premier League. He has since featured for the Qantas Young Socceroos (the Australian under-20 team).

According to his father, the latest member of this remarkable football clan could now bring the Danskin story full circle.

"He has been hoping to get a contract in the Australian Hyundai A League; but if this doesn't happen, he could try his luck in the UK."


Arsenal Ring - New Post

Monday, August 06, 2007

What kind of programmer are you !!!

Your programmer personality type is:

DHSB


You're a Doer.
You are very quick at getting tasks done. You believe the outcome is the most important part of a task and the faster you can reach that outcome the better. After all, time is money.


You like coding at a High level.
The world is made up of objects and components, you should create your programs in the same way.


You work best in a Solo situation.
The best way to program is by yourself. There's no communication problems, you know every part of the code allowing you to write the best programs possible.


You are a liBeral programmer.
Programming is a complex task and you should use white space and comments as freely as possible to help simplify the task. We're not writing on paper anymore so we can take up as much room as we need.


I must say, this test is pretty good, Summarizes my personality perfectly.

Programmer Personality Test


Programming Ring - New Post
Programming Ring - Old Post

Monday, July 30, 2007

Analysis of Algorithms

Part of my MS in Software Systems course was the subject Datastructures and Algorithms. The main reference book was "Datastructures, Algorithms and Applications in C++" by Sartaj Sahni (University of Florida). These are my notes which I had taken based on the above mentioned book.



Performance Analysis of Algorithms

By analysis of a program, we meant the amount of computer memory and time needed to run a program. In performance analysis we use analytical methods to determine the performance of the algorithm. In performance measurement we actually conduct experiments to measure the performance of algorithms. The performances of algorithms are measured based on concepts of Space Complexity and Time Complexity.



What is Space Complexity?

The “Space Complexity” of a program is the amount of memory it needs to run. Space complexity analysis is needed for following reasons.
1) If a program is to be run on a multi-user computer system, then we may need to specify the amount of memory to be allocated to the program.
2) For any computer system, we would like to know in advance whether or not, sufficient memory is available to run the program.
3) A problem might have several possible solutions with which different space requirements can be solved. e.g.:- Different compilers require different memory. Users with less memory will prefer compiler with less memory. So will users having extra memory because it leaves memory for other tasks.
4) We can use space complexity to estimate the size of largest problem that a program can solve.



What is Time Complexity?

The “Time Complexity” of a program is the amount of computer time it needs to run to completion. Time complexity analysis is needed for following reasons.
1) Some computer systems require the user to provide an upper limit on the amount of time the program will run. Once this upper limit is reached the program is aborted. Way out is to specify time limit of few thousand years. This solution could result in serious fiscal problems if the program runs into infinite loops. We would like to provide a time limit that is just slightly above the expected run time.
2) The program we are developing might need to provide a satisfactory real time response. A text editor that takes a minute to move the cursor one page down or up will not be accepted by users. Programs designed for interactive use must provide satisfactory real time response. From the time complexity of the program or program module we can decide whether or not the response time will be accepted.
3) If we have alternative ways to solve a program then the decision on which to use will be based primarily on the expected performance difference among these solutions.




Space Complexity

Components of Space complexity:-
1. Instruction Space :-
Instruction space is the space needed to store the compiled version of the program instructions.
2. Data Space :-
Data Space is the space needed to store all the constant and variable values. It has two components.
a) Space needed by constants and simple variables.
b) Space needed by component variables such as arrays. This includes space needed by structures and dynamically allocated memory.
3. Environment Stack Space :-
The environment stack is used to save information needed to resume execution of partially completed functions.

Instruction Space:-The amount of instruction space that is needed depends on factors such as:-
1) The compiler used to compile the program in to machine code.
2) The compiler options used at the time of compilation. Example: - The overlay option. This is the space assigned only to the program module that is currently executing. When a new module is invoked, it is read in from a disk or other device and the code for the new module overwrites the code of the old module. So program space corresponds to the size of the largest module.
3) The target computer configuration can also affect code size. If the computer has floating point hardware then floating point operators will translate into one m/c instruction per operation. If this hardware is not installed then code to simulate floating point computations will be generated.

Data Space:-For simple variables and constants, the space requirements are functions of the computer and compiler used as well as the size of the numbers involved. The reason is that we will normally be concerned with the number of bytes of memory required. Since the number of bits per byte varies from computer to computer, the numbers of bytes needed per variable also vary.

Environment Stack:-Each time a functions is invoked the following data are saved on the environment stack.
1) The return address
2) The values of all local variables and value formal parameters in the function being invoked.
3) The binding of all reference and constant reference parameters.

Summarizing Space Complexity:-The space needed by program depends on several factors. Some factors are not known at the time the program is written. So until these factors have been determined we cannot make an accurate analysis.
We can determine the contribution of those components that depend on characteristics of the program instance to be solved. The characters typically include factors that determine the size of the problem instance.

eg:- sort n elements :- space required is a function of n
:- add 2 n*n matrices :- we use n instance characteristics

The size of the instruction space is relatively insensitive to the particular problem instance being solved. The contribution of the constants and simple variables to the data structure is also independent of the characteristics of the problem instance to be solved except when the magnitude of the numbers involved becomes too large for the chosen data type in which case we will change the data type or rewrite the program using multi precision arithmetic.

The environment space is generally independent of the instance characteristics unless recursive functions are in use. When recursive functions are used the instance characteristics will generally affect the amount of space needed for the environment stack. The amount of stack space needed by the recursive functions is called the recursion stack space.




Analysis of Space Complexity Problems:-

We can divide the space complexity problem in two parts
a) A fixed part that is independent of the instance characteristics. This part typically includes the instruction space, space of simple variables and space for constants.
b) A variable part that consists of the space needed by component variables whose size depends on the particular problem instance being solved in dynamically allocated space and the recursion stack space.

The space requirement for any program P may be given as

S(P) = C + Sp

where c is a constant that denotes the fixed part of the space requirements and Sp denotes the variable component. An accurate analysis should also include the space needed by temporary variables during compilation. This space is compiler dependent and independent of instance characteristics except in recursive functions.

When analyzing the space complexity of a program we will need to concentrate solely on estimating Sp.

Example:- Sequential Search.
The following code examines a array “a” of “n” elements from left to right to see if one of these elements equals x. If an element equals to x is found, the function returns the position of the first occurrence of x else it returns -1.

template int SequentialSearch( T a[], const T&x, int n)
{
int i;
for(i=0;i<n && a[i] != x; i++);
if(i==n) return -1;
return i;
}


We wish to find space complexity of this function in terms of the instance characteristics n.

Let us assume that T is int.

We need 2 bytes for each of the pointer to the array “a” and the actual parameter corresponding to x; 2 bytes for the formal value parameter n; 2 bytes for the local variable i and 2 bytes for each of the integer constants 0 and -1. The total space needed is 12 bytes. Since this space is independent of n, S(n)=0.
Note that array “a” must be large enough to hold n elements being searched. The space needed by this array is, however, allocated in the function where the actual parameter corresponding to a is declared.




Time Complexity

Components of Time Complexity
Time complexity of a program depends on all the factors that the space complexity depends on. A program will run faster on a computer capable of executing 109 instructions per second than on one that can execute 106 instructions per second.
The time T(P) taken by a program P is the sum of the compile time and the run time. The compile time does not depend on the instance characteristics. The runtime is denotes by Tp.

Because many of factors on which Tp depends on are not known when program is conceived, it is only possible to estimate Tp based on number of additions, subtractions, multiplications, divisions, compare, loading, storing and so on.
Letting n denote the instance characteristics, we might express Tp as

Tp(n) = caADD(n)+csSUB(n)+cmMUL(n)+cdDIV(n)+…

where ca, cs, cm and cd denote the time needed for addition, subtractions, multiplication and division and ADD, SUB, MUL and DIV are functions whose value is the number of additions, subtractions, multiplications and divisions performed when the code is used on an instance with “n” characteristics.
Further, time needed for each arithmetic operation depends on datatypes involved. This makes obtaining exact formulae difficult as we need to separate operation counts by data types.

Two more manageable methods are
1) Identify one or more key operations and determine number of times theses are performed.
2) determine the total number of steps executed by the program.

Operation Counts:-One way to estimate the time complexity of a program or functions is to select one or more operations such as add, multiply and compare to determine how many of each is done. The success of this method depends on ability to identify the operations that contribute most to the time complexity.

Example:- Selection Sort
One strategy to sort an array is to determine the largest element and move it so a[n-1], then determine the largest of the remaining n-1 elements and move it to a[n-2] and so on. For the following program we try to estimate the operation count by counting the number of element comparisons made.

template <classT> void SelectionSort (T a[],int n)
{
for (int size =n; size>1; size--)
{
int pos=0;
for(int i =1; i<n; i++)
if(a[pos] <a[i])
pos=i;
Swap(a[j], a[size-1]);
}
}


When each "i" loop is run, n-1 comparisons are made.
So the total number of comparisons is 1+2+3+...+n-1 = (n-1)n/2.
The number of element moves is 3(n-1), i.e. the Swap function.
So the time complexity of selection sort is (n-1)n/2



Step Counts:-The operation counts method omits accounting for the time spent on all but the chosen operations. In the step count method we attempt to account for the time spent in all parts of function or program. The step count is a function of the instance characteristics. Although any specific instance may have several characteristics (number of inputs, number of outputs, magnitude of input and outputs) the number of steps is computed as a function of some subset of these.
We choose the characteristics that are of interest to us. For example, we might wish to know how the computing time increases as number of input increasing. In this case number of steps will be computed as a function of number of inputs.

Thus before the step count of a program can be determined we need to know exactly which characteristics of the problem instance to be used. These characteristics define not only the variables in the expression for the step count but also how much computing can be counted as a single step. After an instance characteristics have been selected, we can define a step.
A step is any computation unit that is independent of the selected characteristics.

Definition:- A program step is loosely defined to be a syntactically or semantically meaningful segment of a program for which the execution time is independent of the instance characteristics.

We can determine number of steps that a program or function takes to complete a task by creating a global variable count with initial value zero. We introduce into program statements to increment count by the appropriate amount. Therefore each time statement in original program or function is executed, count id incremented by the step count of that statement. The value of count when the program or function terminates is the number of steps taken.

Example:- Sequential Search
We determine the Best case and worst case analysis of this algorithm.

The best case is when first item is the required item.


The worst case is when the search item is not found in the array.


For the average count analysis for a sequential search, assume that the n values in "a" are distinct and that in a successful search, x has equal probability of being any one of these values. Under these assumptions, the average step count for a successful search is the sum of the step counts for the n possible sucessful searches divided by n. To obtain this average, we first obtain step count for the cas x = a[j] where j is in range [0,n-1]





In next blog, I may discuss Asymptotic Notations (i.e. as much as I have understood).
For best understanding, read the book which I have mentioned in the beginning of the blog.

For reference you may visit following sites.
Analysis of Algorithms
http://www.cs.sunysb.edu/~algorith/lectures-good/


Programming Ring - New Post
Programming Ring - Old Post

Thursday, May 31, 2007

Creating .exe using Qmake from QT

Well, didn't find time to write anything or think about writing anything because of loads of issues.

This blog mainly deals with the issue of how to create .exe files when one is using qt libs in code.
A well documented fact which I am putting online for my own reference or rather easy reference. I have taken this from QT faq's long time back. So I don't have the reference link for it.

Suppose one has placed all the files in QPainter folder and wants to create the executable file or a VC project file.

1) Creating Exe.
Qmake –project
Open QPainter.pro and add CONFIG += thread
Qmake –win32 QPainter.pro // This will create a makefile
Nmake –f Makefile

Warning regarding LNK4199 is given but exe still gets created.
Now just run the exe created.


2) For VC++, again after making the above changes in configuration file.

Qmake –project
Open QPainter.pro and add CONFIG += thread
Qmake –t vcapp QPainter.pro –o QPainter.dsp

Now open the dsp in vc, it still will give qt.lib error.
Now edit QPainter.dsp // wow no one told me about this one. tried on my own

In there , there is variable ADD LINK32 which has path to qt.lib. Change qt.lib to qt-mt.lib.

Now the code will run but will give a warning LNK4098:defaultlib “msvcrt.lib” conflicts with use of other libs …

The warning and erors may or may not occur. I have added them because they occurred when I was trying out the executable or VC project creation.


Programming Ring - New Post
Programming Ring - Old Post

Thursday, March 29, 2007

What kind of Superhero or SuperVillian are you

These are results for me... check it out..

What Kind of SuperHero are you ?

Your results:
You are Spider-Man

You are intelligent, witty, a bit geeky and have great power and responsibility.




Spider-Man
75%
Superman
70%
Green Lantern
70%
Robin
55%
The Flash
45%
Supergirl
35%
Wonder Woman
35%
Iron Man
30%
Batman
20%
Hulk
10%
Catwoman
5%


What Kind of SuperVillian are you ?
Your results:
You are Mr. Freeze

You are cold and you think everyone else should be also, literally.



Mr. Freeze
58%
Dr. Doom
51%
Mystique
40%
The Joker
39%
Lex Luthor
38%
Venom
36%
Riddler
36%
Apocalypse
33%
Dark Phoenix
33%
Catwoman
31%
Poison Ivy
30%
Juggernaut
28%
Two-Face
24%
Magneto
23%
Kingpin
21%
Green Goblin
20%


Click here to take the Superhero Personality Test

Click here to take the Supervillain Personality Quiz


General Post Ring - New Post
General Post Ring - Old Post

Friday, March 09, 2007

C++ Questionaire

Some interesting questions asked in C++ tests
Enjoy !!!

1) Will the following program execute?

void main()
{
void *vptr = (void *) malloc(sizeof(void));
vptr++;
}

It will throw an error, as arithmetic operations cannot be performed
on void pointers. It will not build as sizeof cannot be applied to void* ( error “Unknown size” )

However, According to gcc compiler it won’t show any error, simply it executes. but in general we can’t do arthematic operation on void, and gives size of void as 1.
The program compiles in GNU C while giving a warning for “void main”. The program runs without a crash. sizeof(void) is “1″ hence when vptr++, the address is incremented by 1.

However gcc is a C compiler. When compiled in g++, g++ complains that the return type cannot be void and the argument of sizeof() cannot be void. It also reports that ISO C++ forbids incrementing a pointer of type ‘void*’.



2) Will it execute or not?

void main()
{
char *cptr = 0?2000;
long *lptr = 0?2000;
cptr++;
lptr++;
printf(” %x %x”, cptr, lptr);
}

0?2000 cannot be implicitly converted to a pointer.

Compiling with VC7 results following errors:
error C2440: ‘initializing’ : cannot convert from ‘int’ to ‘char *’
error C2440: ‘initializing’ : cannot convert from ‘int’ to ‘long *

Program does executes in C

The printout:
2001 2004

compiled with some warnings:
warning C4047: ‘initializing’ : ‘char *’ differs in levels of indirection from ‘int’
warning C4047: ‘initializing’ : ‘long *’ differs in levels of indirection from ‘int’

Solution is casting needs to be done. The format has to be:
int *a = (int *)2000;



3) Whats the solution ?

#include "iostream.h"

class example
{
private :
int i;
float j;

public :

example (int ii=0, float jj=0.0)
{
i = ii; j = jj;
}

void showdata()
{
cout << i << j;
}

friend example operator *(example k, example l);
};

example operator *(example k, example l)
{
example temp;
temp.i = k.i*l.i;
temp.j = k.j*l.j;
return (&temp);
}

void main ()
{
example e1(10,3.14);
example e2(1,1.5);
example e3,e4,e5;

e3 = e1 * 2;
e4 = 2 * e2;
e5 = e1 * e2 * 2;

e3.showdata();
e4.showdata();
e5.showdata();
}


a) Error "Cannot access private data of class example"
b) Error "No legal conversion of return value to return type class example *"
c) Either a or b
d) Neither a or b


Answer:- (B) :- error C2664: 'example::example(int,float)' : cannot convert parameter 1 from 'example *__w64 ' to 'int'

4) Whats the solution ?

#include "iostream.h"

class Base
{
public:
virtual void fun1()
{
cout << "fun1 of base";
}
};

class der1: public Base
{
public:
void fun1()
{
cout << "fun1 of der1";
}

virtual void fun2()
{
cout << "fun2 of der1";
}
};

class der2 : public der1 {};

void main()
{
Base *b;
der2 d;
b = &d;
b->fun1();
b->fun2();
};


a) Code runs successfully
b) Error: fun2 is not a member of Base
c) Error: cannot convert from class der2 to class Base
d) Error: cannot convert from class Base to class der2

Answer:- (B):- error C2039: 'fun2' : is not a member of 'Base'

5)Whats the solution ?

#include "iostream.h"

class Sample
{
int i;

public:
Sample(Sample S)
{
i=S.i;
}
};

void main()
{
Sample S1;
Sample S2 = S1;
}


a) Error: Class must contain a zero argument constructor;
b) Error: Illegal copy constructor
c) Error: Illegal initialisation
d) None above


Answer:- (A) :- error C2512: 'Sample' : no appropriate default constructor available

6)Whats the output ?

#include "iostream.h"

void main()
{
class xx
{
public:
int x=0;
char name [] = "hello";
};

class xx *s;
cout << s->x;
cout << s->name;
}

Output ?

Answer:-
error C2864: 'main::xx::x' : only static const integral data members can be initialized within a class
error C2864: 'main::xx::name' : only static const integral data members can be initialized within a class

7)Whats the output ?

#include "iostream.h"

class counter
{
unsigned int count;

public:
counter()
{
count = 0;
}

int getcount()
{
return count;
}

void operator ++ (int x)
{
count ++;
}
}

void main()
{
counter c1, c2;
cout<< c1.getcount();
cout<< c2.getcount();
c1 ++;
c2 ++;
cout<< c1.getcount();
cout<< c2.getcount();
}

Output ?

Answer:- 0011

8)Whats the output ?

#include

union base
{
private:
int i;
float j;
};

union derieve:public base
{
private:
int i;
};

void main()
{
cout<< sizeof(union derieve);
}

Output ?

Answer:- error C2570: 'derieve' : union cannot have base classes

9)Whats the solution ?

#include "iostream.h"
#include "malloc.h"

void * operator new (size_t s)
{
void *q = malloc(s);
return q;
}

void main()
{
int *p = new int;
*p = 25;
cout << *p;
}

a) We cannot overload new
b) We cannot overload new globally
c) No problem
d) None above


Answer:- (C) :- On execution, "25" is displated

10)Whats the solution ?

#include "iostream.h"
float divide (float a, int b)
{
return (a/b);
}

float divide(float a, float b)
{
return (a/b);
}

void main()
{
int x=5, y=2;
float n=5.0, m= 2.0;
cout << divide(x,y);
cout << divide (n,m);
}

a) Program will not compile
b) 2, 2.5
c) Compile but display garbage value
d) 2.5, 2.5

Answer:- (D)


Programming Ring - New Post
Programming Ring - Old Post

Thursday, March 08, 2007

C++ Linkages...


Well there are many things in development that one has to learn the hard way. By hard way, I mean one gets stuck in some problem and then fight over it or days. Then when you come to understand the problem, you realize why your peers had implemented a certain thing in a certain way. And when you realize this, you feel through respect for them and never forget the problem ever again.

I went through a same problem. This time I was migrating certain applications from one product which used VC 6.0 to another product which used VC.Net. The newer product was based on the older product, meaning the older product acted as a platform and newer stuff was developed on it. So plugins developed on older product used to work on newer product. The problem used to arise at the time of migration. Since the build system was different (newer product used scons) many modifications where made to #define.

I will briefly talk about problems I faced and reason for them. For most experienced developers, this will be child’s play.



1) LINK 2001:- unresolved external symbol error

a) The .h or .cpp file containing the symbol is not getting included. Meaning the lib which contains the symbol is not getting loaded. Check the Makefile or the Build script files to see that the lib path is include.

b) The Lib might be getting included. In that case, open the lib in notepad and search of the symbol. Check if the symbol is present in the lib file. If it is not, then one has forgotten to do dllexport. ( This is case of implicit linking )

c) In the case of one file including .h file present in another dll. Meaning building one dll but internally there is linking to another dl. Now the second dll, as per __declspec(dllimport) gets imported but some where down it is again getting exported because of __declspec(dllexport). This error will occur mostly in case for static variables of a class. Refer below of method to avoid this problem.



2) LINK 2005:- already defined in obj ….

a) The called dll is getting imported and exported as in case of issue 1c.

b) If the above is not a problem, check whether the functions for which problems exist are inline functions. If they are inline functions then make them non inline. Functions are made inline by either using keyword Inline or by defining them in the class declaration itself.



How to avoid problem of multiple import and export

1) Setup a common environment variable which one can use and forget about the import and export headache

Example:-
Suppose we want to build a dll called TAR and it internally contains number of .h and .cpp file. In one of .h file, usually where one puts all #define or the one being include by all .h and .cpp files we put the following definition

#if defined (_WIN32)
#ifdef DASH_WINEXPORT
#define DASH _WINEXPORT __declspec(dllexport)
#else
#define DASH _WINEXPORT __declspec(dllimport)
#endif
#else
#define DASH _WINEXPORT
#endif



Now in the build script file or the makefile or pro file for the TAR।dll,
make sure to define the variable TAR_WINEXPORT

So now when the TAR dll is being built, the variable TAR_WINEXPORT will get set via the build script. This results in TAR_WINEXPORT being set the value __declspec(dllexport) and all the symbols will get exported.

Now suppose one is building a dll called DASH and one of the files is including a .h file who’s symbolic reference is present in the TAR library. So now when one builds the DASH library, the TAR library will get only imported as in the DASH library building script, we have not set the TAR_WINEXPORT variable. So the value of TAR_WINEXPORT becomes __declspec(dllimport) and hence during building of DASH library, the TAR library will get only imported and not exported out again.

In the DASH library the exporting variable will be as follows

#if defined (_WIN32)
#ifdef DASH_WINEXPORT
#define DASH _WINEXPORT __declspec(dllexport)
#else
#define DASH _WINEXPORT __declspec(dllimport)
#endif
#else
#define DASH _WINEXPORT
#endif



2) In the above case, we have defined two export variables for two
libraries/dll’s. So if number of dll’s increase, number of variables increases.

To avoid that one can simply set one single variable for the whole. Consider the following case.

We have are going to set only one variable for purpose of exporting individually in each file.

Now consider that we have a tar\t.h file which is used for creating TAR library.
Let’s have a dash\d.h file which is internally doing #include<../tar/t.h>. The d.h file is used for creating DASH library. So the layout of both files will be as follows.

d.h

#ifdef _WIN32
#undef GLOBAL_WINEXPORT
#define GLOBAL_WINEXPORT __declspec(dllimport)
#endif



#define DLLIMP
#include "../tar/t.h”
#define undef DLLIMP



#ifndef DLLIMP
#ifdef _WIN32
#undef GLOBAL_WINEXPORT
#define GLOBAL_WINEXPORT __declspec(dllexport)
#endif
#endif


t.h

#ifdef _WIN32
#undef GLOBAL_WINEXPORT
#define GLOBAL_WINEXPORT __declspec(dllimport)
#endif



#ifndef DLLIMP
#ifdef _WIN32
#undef GLOBAL_WINEXPORT
#define GLOBAL_WINEXPORT __declspec(dllexport)
#endif
#endif


So now while linking, when t.h is called, the variable DLLIMP is set. As per the
definition in t.h file, since DLLIMP is set, the __declspec(dllexport) part won’t be called and the dll will only get imported.

When building of TAR dll, since the variable DLLIMP is not set, the dll will get exported out, which is as required.

Generally use solution one as it is easier to manage but it’s all up to developers choice



Programming Ring - New Post
Programming Ring - Old Post

The Name Goremaniac

Well every wondered where the name Goremaniac came from ....

It all began in April 2004. I was working in ANSYS software. One of the hobbies or rather past time for everyone during lunch break was to finish lunch quickly, and then log on to miniclip.com and start playing those flash games.

One of the games was Runescape. I personally never tried it because from description at least i thought it was really confusing. My best friend Raghav however played it and said

"gore, try it man, it is nice and simple"

Well, I created a account called "akadubakadu". It's still alive. !!

Game’s starting point is Lumbridge town. Had no clue what was happening. Walked to the draynor village which lies to west of lumbridge. I was carrying all my stuff with me. Didn’t know how to use the bank exactly. So full loaded with all novice stuff, I went fishing for shrimps. After catching few and cooking them I was getting hang of it.

But nothing is so straight forward in life and also in virtual world. I was there, peacefully fishing, being called a terrorist by some Australia player when suddenly a fish came out from fishing spot and by net disappeared. I was stumped. Had no idea what had happened. When asked people how to get new net, they directed me to Catherby, a members playing area for buying new net. Disappointed I decided to chop some trees and level up my wood cutting. Guess what, tree spirit appeared and killed me.

I was back in lumbridge with only 3 things. Don't remember what those things where, but one was wooden shield. I again made my way to draynor village. This time made my way straight to the bank. However, in between lays a prison. And those prison guards are pretty aggressive. I think I walked pass their fence and they attacked me. I ran foolishly ran inside the fence, and two more attacked me. I was surrounded, however only one can attack at a time in that area. I again died not knowing what mistake I made or why the guards attacked me and not the other players.

So back in Lumbridge, I made a note of not going to draynor again and instead I went north. After crossing the bridge and not being allowed into Al-Kharid, I went straight north. But as usual, my adventure spirit got better of me and diverted from main road and took path from behind the champion's guild. I arrived at the mining area besides the champion’s guild and started mining. All of sudden I was attacked by some character. I thought, why is a player attacking me !!!

All other players around me started shouting
"run noob run !!!"

Well being a noob, I didn’t understand that they where addressing me :D

Well I died.

And that was too much for me. Died thrice in 1 hour. I was furious and wanted to take revenge on the theif who killed me!!! It was actually a non playable character of the game that attacked me.

I had to think of some new name, something reflecting some part of my name. And I came up with Goremaniac. As u might have guess, Gore is my surname.

That's how the characted Goremaniac came to be. And I took my revenge. When I was strong enough, I killed that NPC thief 25 times. And still when I pass via that area, I make it a point to kill it atleast once. :D

Akadubakdu is still alive. I play using that character sometimes. Almost lvl 12 now. Now I think he will be able to get his revenge.

- Goremaniac



General Post Ring - New Post
General Post Ring - Old Post

Monday, February 26, 2007

C++ Interview questions

Well, I will make it short and simple... my company decided not to give us sal. rise and so I started revising my C++ knowledge...

Went through couple of sites and came with these c++ questions (mainly www.coolinterviews.com). To help my fellow job searchers, here are some commonly asked questions in interviews of C++. None of the code nor explanation is mine. So if anyone finds any errors or has some more questions to add to this list please email me at goremaniac@goowy.com

a) How can you force instantiation of a template?

you can instantiat a template in two ways. 1. Implicit instantiation and 2. Explicit Instantion. implicit instatanitioan can be done by the following ways:

template class A {
public:
A(){}
~A(){}
void x();
void z();
};

void main() {
A ai;
A af;
}


External Instantion can be done the following way:

int main() {
template class A;
template class A;
}


b)
class A(){};

int main(){A a;}

Whether there will be a default contructor provided by the compiler in above case ?
yes, if the designer of the class donot define any constructor in the class. then the compiler provides the default constructor in the class.

c) Can we have "Virtual Constructors"?
Yes we cannot have virtual constructors. But if the need arises, we can simulate the implementation of virtural constructor by calling a Init method from the constructor which, should be a virtual function.


d) Can destructor be private?
Yes destructors can be private. But according to Standard Programming practise it is not advisable to have destructors to be private.

e) How do you write a program which produces its own source code as its output?

write this program and save it as pro.c....run....it will show the program to the consol and write the source code into data.txt file...................

#include
void main(){
FILE *fp,*ft;
char buff[100];
fp=fopen("pro.c","r");
if(fp==NULL)
{
printf("ERROR");
}
ft=fopen("data.txt","w+");
if(ft==NULL)
{
printf("ERROR");
}
while(getc(fp)!=EOF)
{
fscanf(fp,"%s",buff);
printf("%s\n",buff);
printf(ft,"%s\n",buff);
}
}




f) Why cant one make an object of abstract class? Give compiler
view of statement


we cant make object of abstract class becoz, in the vtable the vtable entry for the abstract class functions will be NULL, which ever are defined as pure virtual functions...even if there is a single pure virtual function in the class the class becomes as abstract class.. if there is a virtual function in your class the compiler automatically creates a table called virtual function table .. to store the virtual function addresses.... if the function is a pure virtual function the vtable entry for that function will be NULL.even if there is a single NULL entry in the function table the compiler does not allow to create the object.

g) What are Virtual Functions? How to implement virtual functions in "C"
Virtual functio is those function which is basically member function of a base class but define in derrived class .In base class its equal to zero.
For example:

class sum{
public:
void add()=0;
};

class sumderrived{
public:
void add() { cout<<"Sum is 10:"; }
};



h) What is virtual constructors/destructors?

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

In case of inheritance, objects should be destructed exactly the opposite way of their construction. If virtual keyword is not added before base class destructor declaration, then derived class destructor will not at all be called. Hence there will be memory leakage if allocated for derived class members while constructing the object.

Virtual constructor: Constructors cannot be virtual. Declaring a constructor as a virtual function is a syntax error. Does c++ support multilevel and multiple inheritance? Yes. What are the advantages of inheritance? • It permits code reusability. • Reusability saves time in program development. • It encourages the reuse of proven and debugged high-quality software, thus reducing problem after a system becomes functional. What is the difference between declaration and definition? The declaration tells the compiler that at some later point we plan to present the definition of this declaration. E.g.: void stars () //function declaration The definition contains the actual implementation.
E.g.:

void stars () // declarator {
for(int j=10; j>=0; j--) //function body
cout<<”*”;
}



i) Difference between "vector" and "array"?
Vector and ArrayList are very similar. Both of them represent a 'growable array', where you access to the elements in it through an index.ArrayList it's part of the Java Collection Framework, and has been added with version 1.2, while Vector it's an object that is present since the first version of the JDK. Vector, anyway, has been retrofitted to implement the List interface.The main difference is that Vector it's a synchronized object, while ArrayList it's not.While the iterator that are returned by both classes are fail-fast (they cleanly thrown a ConcurrentModificationException when the orignal object has been modified), the Enumeration returned by Vector are not.Unless you have strong reason to use a Vector, the suggestion is to use the ArrayList

j) Difference between "C structure" and "C++ structure".

They are different. C struct can only contain data while C++ struct can contain functions and access limitation such as public, private etc just as a class (not totally the same as class!)


k) What are the different types of polymorphism?

function, operator, virtual function overloading


l) What are the different types of Storage classes?

There are four types of storage class: automatic, register, external, and static


m) Explain "passing by value", "passing by pointer" and "passing by reference"

There is major difference between these three are when we want to avoid making the copy of variable and we want to change value of actual argument on calling function then we use passing by pointer, passing the reference. We can not perform arithmetic operation on reference.


n) Have you heard of "mutable" keyword?

The mutable keyword can only be applied to non-static and non-const data members of a class. If a data member is declared mutable, then it is legal to assign a value to this data member from a const member function.SEE FOLLOWING CODE :- ********************************************

class Mutable{
private :
int m_iNonMutVar;
mutable int m_iMutVar;

public:
Mutable();
void TryChange() const;
};

Mutable::Mutable():m_iNonMutVar(10),m_iMutVar(20) {};

void Mutable::TryChange() const{
m_iNonMutVar = 100; // THis will give ERROR
m_iMutVar = 200; // This will WORK coz it is mutable
}





o) Is there any way to write a class such that no class
can be inherited from it.


Simple, make all constructors of the class private.


p) What is RTTI?
Runtime type identification (RTTI) lets you find the dynamic type of an object when you have only a pointer or a reference to the base type. RTTI is the official way in standard C++ to discover the type of an object and to convert the type of a pointer or reference (that is, dynamic typing). The need came from practical experience with C++. RTTI replaces many homegrown versions with a solid, consistent approach.
RTTI as known Runtime Type Identification. If you want to cast the object of one class as the object of another class so u require to know the type of the object at the runtime and u may want to cofirm is tht object of the same class you want to change we use the typeid operator to check what is the objects type and then use dynamic cast to cast the object.

q) Can you explain the term "resource acquisition is initialization?"
Resource Acquisition is Initialisation or shortly RAII is a term closely connected with exception handling and automatic garbage collection(speaking loosely). RAII is defined as the technique of performing all necessary resource initialisation work right within the body of the constructor itself, and correspondingly doing all the deallocation within the destructor. Since during exception handling destructors of all the classes whose constructors have been successfully invoked, are called therefore all the local objects previously allocated are automatically deallocated without explicitly calling their destructors.the following example explains the RAII technique:

class X{
int *r;

public:
X(){cout<<"X is created"; r=new int[10]; }
~X(){cout<<"X is destroyed"; delete [] r; }

};


class Y{
public:
Y(){ X x; throw 44; }
~Y(){cout<<"Y is destroyed";}
};



Now since Y throws an exception right in its constructor therefore its
destructor won't get called becuse the constructor was not invoked successfully. But the destructor of the class X will definitely be called and therefore the array 'r' will be deallocated. So we didn't have to care about resource deallocation at the time exceptions are raised.


r) What is the difference between "overloading" and "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.

1. Overload - two functions that appear in the same scope are overloaded if they have the same name but have different parameter list
2. main() cannot be overloaded
3. notational convenience - compiler invokes the functions that is the best match on the args – found by finding the best match between the type of arg expr and parameter
4. if declare a function locally, that function hides rather than overload the same function declared in an outer scope
5. Overriding - the ability of the inherited class rewriting the virtual method of a base class - a method which completely replaces base class FUNCTIONALITY in subclass
6. the overriding method in the subclass must have exactly the same signature as the function of the base class it is replacing - replacement of a method in a child class
7. writing a different body in a derived class for a function defined in a base class, ONLY if the function in the base class is virtual and ONLY if the function in the derived class has the same signature
8. all functions in the derived class hide the base class functions with the same name except in the case of a virtual functions which override the base class functions with the same signature


s) What happens to the member pointers when an exception occures in constructor, while allocating memory ? how can we over come this ?

Offcourse it will result memory leak.... so use auto_ptr for such thing .. see following example, i have used two types to avoid memory leaks one is auto_ptr and another is initialize function

#include
#include

class DataClass{
public:
int m_iValue;
DataClass(int i =0):m_iValue(i){}

void show(void) {
// Because of the moronic html of the blogger, i am not able to show std::cout
// statements, that's why i have converted them to printf's for now
printf ("Value :- %d \n",m_iValue);
}
};

class ResourceLeakFreeClass{
public:
std::auto_ptr m_Data1;
DataClass * m_Data2;ResourceLeakFreeClass():m_Data1(new DataClass(100)),
m_Data2(InitDataClass(200)){}

~ResourceLeakFreeClass(){
if(m_Data2){
delete m_Data2;
m_Data2 = 0; }
}

DataClass * InitDataClass(int iData) {
try{
return new DataClass(iData);
}
catch (...) {
delete m_Data2;throw;
}
}
};

int main(int argc, char* argv[]) {
ResourceLeakFreeClass RLFC;
RLFC.m_Data1->show();
RLFC.m_Data2->show();
return 0;
}



t) Can we take "main function" as of type float,char etc?

Its possible only with int.If a function is declared as void that it may return anything by default.


u) what are auto static variables and auto extern variables?

In theory these are called storage classes. These will define the scope and life time of variables or functions.There are mainly 4 of them:auto is the default storage class for local variables. register is used to define local variables that should be stored in a register instead of RAM. This means that the variable has a maximum size equal to the register size say a word.static can also be defined within a function or as a global variable. If this is done, the variable is initialized at compilation time and retains its value between calls ie, inside the function. Because it is initialed at compilation time, the initialization value must be a constant. This is serious stuff - tread with care. extern defines a variable as global one ie, that is visable to all files irrespective of where it is defined. When you use 'extern' the variable cannot be initalized as all it does is point the variable name at a storage location that has been previously defined.


v) What will happen if I say delete this

if you say "delete this", you are effectively calling the destructor twice, which could well be a disaster if your class uses heap. The destructor will be called when you say " delete this " and again when that object goes out of scope. Since this is the language behavior, there is no way to prevent the destructor from being called twice. Please refrain from forcibly calling a destructor or using clause like this. For more information, visit the following link: http://www.parashift.com/c++-faq-lite/dtors.html

destructor executed, but memory will not be freed (other than work done by destructor). If we have class Test and method Destroy { delete this } the destructor for Test will execute, if we have Test *var = new Test()
1. pointer var will still be valid
2. object created by new exists until explicitly destroyed by delete
3. space it occupied can be reused by new
4. delete may only be applied to a pointer by new or zero, applying delete to zero = no FX
5. delete = delete objects
6. delete[] – delete array
7. delete operator destroys the object created with new by deallocating the memory assoc. with the object
8. if a destructor has been defined fir a class delete invokes that desructor


w) We can overload assignment operator as a normal function. But we can not overload assignment operator as friend function why?

If the operation modifies the state of the class object, it operates on, it must be a member function, not a friend function. Thus all operator such as =, *=, +=, etc are naturally defined as member functions not friend functions. Conversely, if the operator does not modify any of its operands, but needs only a representation of the object, it does not have to be a member function and often less confusing. This is the reason why binary operators are often implemented as friend functions such as + , *, -, etc..


x) What do you mean by binding of data and functions?

Encapsulation


y) Difference between a "assignment operator" and a "copy constructor"

Copy constructor is called every time a copy of an object is made. When you pass an object by value, either into a function or as a function's return value, a temporary copy of that object is made. Assignment operator is called whenever you assign to an object. Assignment operator must check to see if the right-hand side of the assignment operator is the object itself. It executes only the two sides are not equal

1. constructor with only one parameter of its same type that assigns to every nonstatic class member variable of the object a copy of the passed object
2. copy assignment operator must correctly deal with a well constructed object - but copy constructor initializes uninitialized memory
3. copy constructor takes care of initialization by an object of the same type x
4. for a class for which the copy assignment and copy constructor not explicitly declared missing operation will be generated by the compiler. Copy operations are not inherited - copy of a class object is a copy of each member
5. memberwise assignment: each member of the right hand object is assigned to the corresponding member of the left hand object
6. if a class needs a copy constructor it will also need an assignment operator
7. copy constructor creates a new object, assignment operator has to deal w/ existing data in the object
8. assignment is like deconstruction followed by construction
9. assignment operator assigns a value to a already existing object
10. copy constructor creates a new object by copying an existing one
11. copy constructor initializes a freshly created object using data from an existing one. It must allocate memory if necessary then copy the data
12. the assignment operator makes an already existing object into a copy of an existing one.
13. copy constructor always creates a new object, assignment never does


z) What are the things contains in .obj file ? ( compiled result of .cpp file )

C++ .obj file holds code and data suitable for linking with other object files to create an executable or a shared object file.


a1) What is importance of const. pointer in copy constructor?

Because otherwise you will pass the object to copy as an argument of copy constructor as pass by value which by definition creates a copy and so on... an infinite call chain....


b1) What is the Basic nature of "cin" and "cout" and what concept or principle we are using on those two?

Basically "cin and cout" are INSTANCES of istream and ostream classes respectively.And the concept which is used on cin and cout is operator overloading. Extraction and Insertion operators are overloaded for input and ouput operations.


c1) What is abstraction?
Abstraction is of the process of hiding unwanted details from the user.


d1) What is the difference between macro and inline()?

1. Inline follows strict parameter type checking, macros do not.
2. treated like macro definitions by C++ compiler
3. meant to be used if there’s a need to repetitively execute a small block if code which is smaller
4. always evaluates every argument once
5. defined in header file
6. avoids function call overload because calling a function is slower than evaluating the equivalent expression
7. it’s a request to the compiler, the compiler can ignore the request
2. Macros are always expanded by preprocessor, whereas compiler may or may not replace the inline definitions.


e1) what is the use of volatile keyword? Give me one example?

(P876 from textbook C++ How To Program:)The volatile type qualifier is applied to a definition of a variable that may be altered from outside the program (i.e., the variable is not completely under the control of the program). Thus, the compiler cannot perform optimizations (such as speeding program execution or reducing memory consumption, for example) that depend on "knowing a variable's behavior is influenced only by program activities the compiler can observe."(notes:)1) volatile indicate the object is modified by something not directly under the compiler's control (i.e., the hardware itself)2) one use of volatile qualifier is to provide access to memory locations used by asynchronous processes such as interrupt handlers.3) Another example might be the global variables that keeps track of the total number of timer interrupts.


f1) Dynamic Binding

· delaying until runtime the selection of which function to run
· refers to the runtime choice of which virtual function to run based on the underlying type of the object to which a reference or a pointer is based
· applies only to functions declared as virtual when called thru reference or ptr
· in C++ dynamic binding happens when a virtual function is called through a reference ( ptr) to a base class. The face that ref or ptr might refer to either a base or a derived class object is the key to dynamic binding. Calls to virtual functions made thru a reference or ptr are resolved at run time: the function that is called is the one defined by the actual type of the object to which the reference or pointer refers


g1) Rule of 3

· if a class needs a destructor, it will also need an assignment operator and copy constructor
· compiler always synthesizes a destructor for us
· destroys each nonstatic member in the reverse order from that in which the object was created
· it destroys the members in reverse order from which they are declared in the class1. if someone will derive from your class2. and if someone will say new derived where derived is derived from your class3. and if someone will say delete p, where the actual objects type is derived but the pointer ps type is your class
· make destructor virtual if your class has any virtual functions



h1) Why is the pre-increment operator faster than the post-increment operator?

pre is more efficient that post because for post the object must increment itself and then return a temporary containing its old value. True for even built in types


i1) How to implement virtual functions in C

keep function pointers in function and use those function ptrs to perform the operation


j1) Find minimum and maximum of two numbers

int x; // we want to find the minimum of x and y
int y;
int r; // the result goes here
r = y + ((x - y) & -(x < y)); // min(x, y)
r = x - ((x - y) & -(x < y)); // max(x, y)


The above solution is taken from site Bit Twiddling Hacks By Sean Eron Anderson
On his site, Sean Eron Anderson has given many bit twiddling hacks for C. Do refer to the following site for it.

http://graphics.stanford.edu/~seander/bithacks.html


k1) Can you return by Reference in a function? What are advantages of References as Function Return Types ?

Yes.
Functions may return references. The formats are

Type & function_name(signature);
const Type & function_name(signature);


The compiler actually returns a pointer in both formats, but a
caller does not use pointer notation (*, ->) with the result. In the second format, const makes the compiler report errors if a caller tries to modify the result as an lvalue. Returning references from functions is important with structure types for improving performance. When you return a reference to a structure type from a function call, the compiler returns a pointer instead of a copy.

Another use of references with function returns is cascading. This technique allows you to embed function calls, as follows.

function_name(function_name(function_name(args)));


To see why references are appealing with cascading, consider following code

inline int *bump(int *p) {
++*p; // increment by one
return p; // return pointer
}

int num = 10;
cout << *bump(bump(&num)) << endl; // displays 12


We embed bump() calls in the cout statement because bump() now
returns its first argument, which is a pointer to an integer. We must, however, use & to pass the address of num in the first call to bump() and use * to dereference the return value from the second bump() call. If we forget to dereference (*), the program still compiles and runs, but displays an address (pointer to an integer) instead of the correct answer 12.

References make this simple. Here's the code.

inline int & bump(int & m) {
return ++m; // increment by one
}

int num = 10;
cout << bump(bump(num)) << endl; // displays 12


With references, the compiler supplies the pointers to pass function
arguments and return values. Embedded calls to bump(), therefore, do not require pointer notation.

For further details refer
http://www.phptr.com/articles/article.asp?p=31783&seqNum=3&rl=1

All together, refer this link to find 100 interview questions.
http://www.techinterviews.in/?p=18


Cheers
-Goremaniac !!!


Programming Ring - New Post

Wednesday, January 31, 2007

SEASON OF MARRIAGES !!!!

Well I had to put up this blog. So many friends are getting married, I have lost the count. Actually I sat down and in past 2 hours came up with a list.

Season of marriages began on 17th Nov. 2006 when Chitnis got engaged and will end in
June 2007.

In between that, my number of friends are getting married or engaged.
This doesnot include all the surprise announcements which I am sure some more of my friends will make.

I just hope they don't get offended by me publishing their marriage dates in public.

17 Nov 2006 - Venkatesh Chitnis - Engagement
25 Nov 2006 - Adam Jones - Marriage
26 Nov 2006 - Abhijit Gadgil - Marriage
26 Nov 2006 - Sudipta Basu - Marriage
13 Dec 2006 - Pranay Tembhekar - Marriage
13 Dec 2006 - Yogesh Deodhar - Marriage
14 Dec 2006 - Prasad mahajan - Marriage
14 Dec 2006 - Raghavendra Pai - Marriage
* Dec 2006 - Amol Gawai - Engagement
24 Dec 2006 - Sanket Joshi - Engagement
24 Jan 2007 - Amol Gawai - Marriage
24 Jan 2007 - Rohit Khare - Marriage
28 Jan 2007 - Vinu Thiagrajan - Marriage
28 Jan 2007 - Ajit Khaparde - Engagement
28 Jan 2007 - Deepak Shah - Marriage
29 Jan 2007 - Kapil Rajopadhaye - Marriage
4 Feb 2007 - Omkar Karandikar - Engagement
11 Feb 2007 - Niranjan Joshi - Engagement
20 Feb 2007 - Sunil Nakum - Marriage
25 Feb 2007 - Ajit Khaparde - Marriage
4 May 2007 - Venkatesh Chitnis - Marriage
10 May 2007 - Omkar Karandikar - Marriage
4 Jun 2007- Sanket Joshi - Marriage
8 Jul 2007 - Niranjan Joshi - Marriage

Well the list keeps on increasing... I will edit and keep on adding more....

General Post Ring - New Post
General Post Ring - Old Post