Wednesday, 9 July 2014

OOPS

1. The Object Oriented Programming Languages directly represent the real life objects like Car,Account,Customer etc. The features of the OO programming languages like polymorphism, inheritance and encapsulation (PIE) make it powerful.
2. The key benefits of OOPS are:


  • Re-use of previous work: using implementation inheritance and object composition.
  • Real mapping to the problem domain: Objects map to real world and represent vehicles, customers, products etc: with encapsulation.
  • Modular Architecture: Objects, systems, frameworks etc are the building blocks of larger systems.

The increased quality and reduced development time are the by-products of the key benefits discussed above.
3. Inheritance("is-a) relationship is UniDirectional. Eg :  House is a Building but Building is not a house.
4. Composition is "has-a" relationship. Eg: House has a bathroom.
5. Problem with class inheritance is that the subclass becomes dependent on the parent class implementation.
This makes it harder to reuse the subclass, especially if part of the inherited implementation is no longer desirable and hence can break encapsulation. Also a change to a superclass can not only ripple down the inheritance hierarchy to subclasses, but can also ripple out to code that uses just the subclasses making the design fragile by tightly coupling the subclasses with the super class. But it is easier to change the interface/implementation of the composed class.
6. Encapsulation – refers to keeping all the related members (variables and methods) together in an object. Specifying member variables as private can hide the variables and methods. Objects should hide their inner workings from the outside view. Good encapsulation improves code modularity by preventing objects interacting with each other in an unexpected way, which in turn makes future development and refactoring efforts easy.

7. Abstract classes let you define some default behavior and force subclasses to provide any specific behavior.
8. Overloading deals with multiple methods in the same class with the same name but different method signatures. Overloading lets you define the same operation in different ways for different data.
9. Overriding deals with two methods, one in the parent class and the other one in the child class and has the same name and  signatures. Overriding lets you define the same operation in different ways for different object types.
10. Serialization is a process of reading or writing an object. It is a process of saving an object’s state to a sequence of bytes, as well as a process of rebuilding those bytes back into a live object at some future time.
common use of serialization is to use it to send an object over the network or if the state of an object needs to be persisted to a flat file or a database.
11. Polymorphism: The same message sent to different objects, results in behavior that is dependent on the nature of the object receiving the message.
12. Abstraction : is the process where ideas are distanced from the concrete implementation of the objects. The concrete implementation will change but the abstract layer will remain the same.
Let us look at an analogy:
When you drive your car you do not have to be concerned with the exact internal working of your car (unless you are a mechanic). What you are concerned with is interacting with your car via its interfaces like steering wheel, brake pedal, accelerator pedal etc. Over the years a car’s engine has improved a lot but its basic interface has not changed (i.e. you still use steering wheel, brake pedal, accelerator pedal etc to interact with your car). This means that the implementation has changed over the years but the interface remains the same. Hence the knowledge you have of your car is abstract.

13. Loose coupling: The process of making objects independent of each other rather than dependent of one another.Loosely coupled objects are easier to reuse and change.
14. A class which declares or inherits a virtual function is called a polymorphic class 


Monday, 7 July 2014

MultiThreading Basics

  1. A thread has its own program counter (PC), a register set, and a stack space. Threads are not independent of one other like processes as a result threads shares with other threads their code section, data section and OS resources like open files and signals.
  2.  In a multi-threaded application each thread will have its own stack but will share the same heap. This is why care should be taken in your code to avoid any concurrent access issues in the heap space. 
  3. The stack is thread-safe because each thread will have its own stack with say 1MB RAM allocated for each thread but the heap is not thread-safe unless guarded with synchronization through your code.
  4. A process is an execution of a program but a thread is a single execution sequence within the process. A process can contain multiple threads. A thread is sometimes called a lightweight process.
  5. Without synchronization, it is possible for one thread to modify a shared object while another thread is in the process of using or updating that object’s value. This often causes dirty data and leads to significant errors. The disadvantage of synchronization is that it can cause deadlocks when two threads are waiting on each other to do something. Also synchronized code has the overhead of acquiring lock, which can adversely affect the performance
  6. Synchronization Example: If you imagine an application in which one thread (the producer) writes data to a file while a second thread (the consumer) reads data from the same file. In this example the concurrent threads share the same resource file. Because these threads share the common resource file they should be synchronized. Also these two threads should communicate with each other because the consumer thread, which reads the file, should wait until the producer thread, which writes data to the file and notifies the consumer thread that it has completed its writing operation.
  7. Process-based multitasking handles the concurrent execution of programs. Thread-based multitasking deals with the concurrent execution of pieces of the single program.
  8. The principal advantage of multithreading is that it enables you to write very efficient programs because it lets you utilize the idle time that is present in most programs.If all shared data is read-only, there’s no problem, because the data read by one thread is unaffected by whether or not another thread is reading the same data. However, if data is shared between threads, and one or more threads start modifying the data, there’s a lot of potential for trouble. In this case, you must take care to ensure that everything works out OK. 
  9. Suppose you’re buying tickets to see a movie at the cinema. If it’s a big cinema, multiple cashiers will be taking money, so more than one person can buy tickets at the same time. If someone at another cashier’s desk is also buying tickets for the same movie as you are, which seats are available for you to choose from depends on whether the other person actually books first or you do. If there are only a few seats left, this difference can be quite crucial: it might literally be a race to see who gets the last tickets.This is an example of a race condition: which seats you get (or even whether you get tickets) depends on the relative ordering of the two purchases.
  10. Critical section is group of instructions/statements or region of code that need to be executed atomically, such as accessing a resource (file, input or output port, global data, etc.).
  11. A simple solution to critical section can be thought as shown below
    acquireLock();
    Process Critical Section
    releaseLock();
  12. A thread must acquire a lock prior to executing critical section.
  13. A reentrant function is one that can safely be executed in parallel by multiple threads of execution.
  14. A Reentrant Function shall satisfy the following conditions,
    • Should not call another non-reentrant function
    • Should not access static life time variables (static/extern)
    • Should not include self modifying code

  15. Every thread safe function is reentrant, but the converse need not be true. A thread safe function can be called from multiple threads even when the function accessing shared data.
  16. A mutex is locking mechanism used to synchronize access to a resource. Only one task (can be a thread or process based on OS abstraction) can acquire the mutex. It means there will be ownership associated with mutex, and only the owner can release the lock (mutex).
  17. Semaphore is signaling mechanism.
  18. It makes application more responsive as computations are done in different  thread.
  19. Multithreaded programming is also a useful paradigm for performing time-consuming operations without freezing the user interface of an application.
  20. Process-based multitasking handles the concurrent execution of programs. Thread-based multitasking deals with the concurrent execution of pieces of the same program.The principal advantage of multithreading is that it enables you to write very efficient programs because it lets you utilize the idle time that is present in most programs. 

Static and Dynamic Libraries

Static
Dynamic
Static libraries are compiled into the program itself.
Shared libraries are compiled separately and referenced by the program
Program Size increases 
Program size is smaller but shared libraries are required at the runtime.
Every program has its own static library
Shared library has only one copy and referenced by different programs

  • Libraries donot contain main method.

Saturday, 5 July 2014

Algorithms- Things to Remember

  1. Height of a node is number of edges on longest path from node to leaf.Height of leaf is 0.
  2. Depth of a node is number of edges from node to root of the tree. Depth of root is 0.           
  3.  Maximum number of edges that can exist in Directed Acyclic Graph is n(n-1)/2
  4.  Insertion into BST  takes O(nlogn) time.


      



Thursday, 3 July 2014

Static Data Member and Member Functions in a Class-- Facts

1. Static data members of a class should be defined( it is declared inside the class) outside the class to allocate the storage location.
2. Static member functions are independent of any object of a class.They dont have access to this pointer of a class
3. Static Data Member and member functions are  accessed using classname and scope resolution operator(::).
4. A static member function can only access static data members, static member functions and any other functions  from outside the class.
5. Static member functions cannot be virtual,volatile,const,const volatile.
6. Static member functions donot have access to non static data members/member functions.The vptr is non static data member , hence static member functions cant access it.


Please comment if you find anything incorrect or have any other input

Tuesday, 1 July 2014

C++ -- Things to Know



  1. Constructor is a special member function that is automatically called by compiler when object is created and destructor is also special member function that is also implicitly called by compiler when object goes out of scope. They are also called when dynamically allocated object is allocated and destroyed, new operator allocates storage and calls constructor, delete operator calls destructor and free the memory allocated by new.
  2. Constructors and destructors both can be called implicity and explicitly.
  3. Explicit call to destructor is only necessary when object is placed at particular location in memory by using placement new. Destructor should not be called explicitly when the object is dynamically allocated because delete operator automatically calls destructor. 



class A

{

public:

    A()

    {



    }


    ~A()


    {





    }


};
void Func()
{
    char mem[sizeof ( A )];
    void* p = mem;
    A* f = new ( p ) A(); // f points to mem
    f->~A();   // Explicitly call the destructor
}

4. To use auto_ptr<A> b(new A) , use <memory> header.
5. Copy Constructor and Assignment operator are provided default by compiler.
6. C++ has direct access to low-level functionality provided by the operating system. This is one of the reasons C++ can produce higher performance code.
7. Class variables are called static variables. There is only one occurrence of a class variable.
8. Instance variables are non-static and there is one occurrence of an instance variable in each class instance (i.e. each object). Also known as a member variable or a field.
9. Idempotent methods are methods, which are written in such a way that repeated calls to the same method with the same arguments yield same results.
10. By default all the functions defined inside the class are implicitly or automatically considered as inline except virtual functions (Note that inline is a request to the compiler and its compilers choice to do inlining or not).
11.Static variables are initialized when complied. And compiler will allocate memory to all the global and static variables in BSS(Block Started by symbol) segment before the main function is executed. Main function is not the first thing we do when we execute a program.
12. Static object are initialized only once and live until the program terminates.
13. Local Objects are called stack based or automatic objects
14. Global static objects are called and initialized before main.
15.  References in C++ cannot be used for implementing data structures like Linked List, Tree.
16. main is not a reserved word in  C++.
17.  A callback is a pointer to a function, so if you want a processing function to notify you about some event you pass a pointer to another function (the callback) to the processing function.The processing function then calls the callback when appropriate
18. Callbacks have two fundamental flaws: Firstly, they are not type-safe. We can never be certain that the processing function will call the callback with the correct arguments. Secondly, the callback is strongly coupled to the processing function since the processing function must know which callback to call.
19. Pre increment/decrement can be used a l- value but post increment/decrement cannot be used as   l-value.
      ++b = 20; // works
b++=200 // not works
20.When a function is declared as const, it can be called on any type of object. Non-const functions can only be called by non-const objects.
21. Friends declarations may appear anywhere in the class.They are not members of class granting friendship and so they are not affected by access control section of class in which they are declared.
22. We need to use Initializer list whenver we have const or reference data members. The normal constructor we use do assignments and we cannot assign to const objects or objects of refernece types.We can only intialize which is done by intializer list.
23. To prevent copies, class must explicitly declare its copy constructor as private.However, members and friends can still make copies. If we want to prevent this we do so by declaring copy constructor as private but not defining it.
24. ++i is faster than i++ because i++ has to make a copy of the object and ++i does not.
25.By default, the first enum has the value 0.
26. If you mark the constructor as private, if you extend that class,..then you wont be able to instantiate the derived class as well.
27.  Constructors that are used to allocate memory on the
heap for the pointers inside a class are known as Dynamic constructors.
28. Cannot be invoked explicitly like a normal method call on the object
           A a1;
           a1.A(); // Cannot invoke a constructor like a normal method



References: 
  1. http://www.geeksforgeeks.org/static-objects-destroyed/
  2. http://www.geeksforgeeks.org/possible-call-constructor-destructor-explicitly/
d more at http://www.devarticles.com/c/a/Cplusplus/Multithreading-in-C/#UbytrIzR3xEwfvFR.9

Find an element occuring odd number of times

Given an array a, find an element occuring odd number of times, all other elements occur even number of times

Approach

XOR all the elements of an array, the result will be the element occuring odd number of times. (Refer http://en.wikipedia.org/wiki/Bitwise_XOR#XOR for more information on XOR)

Input:       An array of size n.
Output:    Elements that appear odd number of times

Example: 
Input:       7
                1,2,3,3,2,6,1
Output:    6 


#include<iostream>
using namespace std;

int FindElement ( int * a, int n )
{
    int res=0;
    for ( int i=0; i<n; i++ )
    {
        res^=a[i];
    }
    return res;
}
int main()
{
    int n;
    cin>>n;
    int *a=new int[n];
    for ( int i=0; i<n; i++ )
    {
        cin>>a[i];
    }
    cout<< FindElement ( a,n );
    free ( a );

    getchar();

}


Please comment if you find anything incorrect or have any other inputs.