Sunday, September 14, 2014

C++ Contd..

Templates Mutex BST Linked List Hash Function Design Patterns

C++ Copy Constructor, Assignment Operator

Copy Constructor

Song(Song const&);
It is needed if you want to initialize an object to take the value of another one:
Song a;
Song b = a;    // Calls copy constructor
Assignment Operator
void operator=(const Song&);
It is needed for assigning a value to an already existing instance:
Song a;
Song b;
b = a;        // Calls assignment operator
Note that the standard return value for an assignment operator is a reference:
Song& operator=(const Song&);

C++ Singleton

#include <iostream>

using namespace std;

class Singleton
{
    public:
        static Singleton& getInstance()     // See Note 1.
        {
            static Singleton instance;      // See Note 2.
                                            // Guaranteed to be destroyed.
                                            // Instantiated on first use.
            return instance;
        }

        void Print();

    private:
        Singleton() {};                     // Constructor? (the {} brackets) are needed here.
                                            // Dont forget to declare these two. You want to make sure they
                                            // are unaccessable otherwise you may accidently get copies of
                                            // your singleton appearing.
        Singleton(Singleton const&);        // Copy Constructor. Don't Implement
        void operator=(Singleton const&);   // Assignment Operator. Don't implement
};

void Singleton::Print()
{ 
    cout << "I am a singleton" << endl;
}

int main(int argc, char *argv[])
{
    Singleton &S1 = Singleton::getInstance();    // Create/Instantiate Singleton 
    S1.Print();
    Singleton::getInstance().Print();

    system("PAUSE");
    return EXIT_SUCCESS;
}

Note 1. Why does everybody want to return a singleton as a pointer? Returning it as a reference seems much more logical! You should never be able to free a singleton manually. How do you know who is keeping a reference to the singleton? If you don't know (or can't guarantee) nobody has a reference (in your case via a pointer) then you have no business freeing the object. Note 2. Use the static in a function method. This guarantees that it is created and destroyed only once. It also gives you lazy initialization for free. This also means I don't need to add the object as a member because I have a static function with a static object inside it? Exactly, the object lives from first call to program termination, so it cannot be a plain data member. Note: Use a Singleton if:

  • If you need to have one and only one object of a type in system
Do not use a Singleton if:
  • If you want to save memory
  • If you want to try something new
  • If you want to show off how much you know
  • Because everyone else is doing it (See cargo cult programmer in wikipedia)
  • In user interface widgets
  • It is supposed to be a cache
  • In strings
  • In Sessions
  • I can go all day long
How to create the best singleton:
  • The smaller, the better. I am a minimalist
  • Make sure it is thread safe
  • Make sure it is never null
  • Make sure it is created only once
  • Lazy or system initialization? Up to your requirements
  • Sometimes the OS or the JVM creates singletons for you (e.g. in Java every class definition is a singleton)
  • Provide a destructor or somehow figure out how to dispose resources
  • Use little memory
If you need one and only one object, you create one and only one.
If there is no logical way that two instances could ever be accommodated without irreversibly corrupting the application, you should consider making it a singleton.
And then there's the other aspect, global access: If you don't need global access to the instance, it shouldn't be a singleton.

Thursday, September 11, 2014

C++ Object Slicing

"Slicing" is where you assign an object of a derived class to an instance of a base class, thereby losing part of the information - some of it is "sliced" away. For example,
class A {
   int foo;
};

class B : public A {
   int bar;
};
So an object of type B has two data members, foo and bar Then if you were to write this:
B b;

A a = b;
Then the information in b about member bar is lost in a. Situations where problems would arise If You have a base class A and a derived class B, then You can do the following.
void wantAnA(A myA)
{
   // work with myA
}

B derived;
// work with the object "derived"
wantAnA(derived);
Now the method wantAnA needs a copy of derived. However, the object derived cannot be copied completely, as the class B could invent additional member variables which are not in its base class A. Therefore, to call wantAnA, the compiler will "slice off" all additional members of the derived class. The result might be an object you did not want to create, because it may be incomplete, it behaves like an A-object (all special behaviour of the class B is lost).

C++ Interface Example

#include <iostream>
#include <vector>

using namespace std;

// Animal attribute/property is common between Cow and Dog, hence this is the interface
// that contains pure virtual functions of the property that is common to Cow and Dog
// Since this is pure abstract class (since it has a pure virtual function), this class 
// cannot be instantiated.
class Animal
{
public:
    virtual void Speak() const = 0;
};

// Note:
// You can have an implementation of a pure virtual function.
// A derived class can explicitly call the base class implementation (if access permissions are allow it) 
// by using a fully-scoped name (by calling Animal::Speak(), if Animal::Speak() is public or protected (i.e. not private).

// The use case can be when there's a more-or-less reasonable default behavior, but the class 
// designed wants that sort-of-default behavior to be invoked only explicitly. 
// It can also be the case what you want derived classes to always perform their own work but also be able to call a common set of functionality.

// The other use could be for the case when you want to create a pure abstract class, but it does not have a pure virtual function.
// In that case you can make the destructor a pure abstract method and create the implementation for the destructor.

// Note that even though it's permitted by the language, it's not something that I see commonly used 
// (and the fact that it can be done seems to surprise most C++ programmers, even experienced ones).

void Animal::Speak() const
{
    cout << "Make some noise" << endl; 
}

class Cow : public Animal
{
public:
    void Speak() const;
};

void Cow::Speak() const
{
    cout << "Moo" << endl;
}

class Dog : public Animal
{
public:
    void Speak() const;
};

void Dog::Speak() const
{
    cout << "Woof" << endl;
}

void Speak(const Animal& animal)    // 1. Since we are passing a const reference, this can only call a const member function.
{                                   //    So we will have to make Animal::Speak() const and in turn Cow::Speak() and Dog::Speak() const
    animal.Speak();                 // 2. Passing a non const reference will let you modify Animal
}                                   // 3. Passing by value will lead to object slicing

int main(int argc, char *argv[])
{
    Cow myCow;
    Dog myDog;

    vector<Animal*> animalVec;      // You can't instantiate abstract classes, thus a vector of abstract classes can't work.
                                    // You can however use a vector of pointers to abstract classes.
                                    // Also storing by value i.e. vector<Animal> animalVec; will lead to object slicing
    animalVec.push_back(&myCow);
    animalVec.push_back(&myDog);

    for(vector<Animal*>::iterator iter = animalVec.begin(); iter != animalVec.end(); ++iter)
    {
        Speak(**iter);
    }

    system("PAUSE");
    return EXIT_SUCCESS;
}
Output:
Moo
Woof
Press any key to continue . . .

Wednesday, September 10, 2014

C/C++ Array

One dimensional array
                int foo [5];    // Array contains integers
            
Initialize: foo [5] = {1, 2, 3, 4, 5}; foo [5] = {1, 2, 3,}; // 3rd and 4th element are assigned zero foo [5] = {}; // All elements are assigned zero foo [] = {1, 2, 3, 4, 5}; Function: void procedure (int arg[]); Pass by value: Pass by reference: procedure (foo); Pass by pointer:
Two dimensional array
                int foo [2][3];     // [row x col] Array contains integers
                                    // Total row*col elements
            
Initialize: foo [2][3] = {{1, 2, 3}, {4, 5, 6}}; foo [2][3] = {1, 2, 3, 4, 5, 6}; foo [][] = {{1, 2, 3}, {4, 5, 6}}; foo [][] = {1, 2, 3, 4, 5, 6}; foo [2][3] = {{1, 2, 3}}; // All rest elements are assigned zero foo [2][3] = {}; // All elements are assigned zero

C/C++ Storage Classes

auto Default storage class for all local variables. Can only be used within functions, i.e., local variables.
register 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 (usually one word) and can't have the unary '&' operator applied to it (as it does not have a memory location). It should only be used for variables that require quick access such as counters. It should also be noted that defining 'register' does not mean that the variable will be stored in a register. It means that it MIGHT be stored in a register depending on hardware and implementation restrictions.
static Instructs the compiler to keep a local variable in existence during the life-time of the program instead of creating and destroying it each time it comes into and goes out of scope. Therefore, making local variables static allows them to maintain their values between function calls. The static modifier may also be applied to global variables. When this is done, it causes that variable's scope to be restricted to the file in which it is declared. In C++, when static is used on a class data member, it causes only one copy of that member to be shared by all objects of its class.
extern Defines a global variable that is visible to ALL object modules. When you use 'extern' the variable cannot be initialized as all it does is point the variable name at a storage location that has been previously defined.
mutable (C++) Applies only to C++ class objects. It allows a member of an object to override constness. That is, a mutable member can be modified by a const member function.

Monday, September 8, 2014

C++ #define Vs typedef

#define typedef
Is a preprocessor token: the compiler itself will never see it. Is a compiler token: the preprocessor does not care about it.
Obeys scoping rules just like variables. Stays valid until the end of the file (or until a matching undef).
Is a preprocessor directive used to define macros or general pattern substitutions. For eg. #define MAX 100, substitutes all occurrences of MAX with 100 Creates an "alias" to an existing data type. For e.g. typedef char chr;
            #define INTPTR int*
            ...
            INTPTR a, b;
            
After preprocessing, that line expands to
            int* a, b;
            
Only a will have the type int *; b will be declared a plain int (because the * is associated with the declarator, not the type specifier).
        typedef int *INTPTR;
        ...
        INTPTR a, b;
        
In this case, both a and b will have type int *.

Sunday, September 7, 2014

C++ Const keyword

You have to read pointer declarations right-to-left.

            const int x = 10;
            
x's value cannot be changed
            int const x = 10;
            
Same as above
            static int x = 10;
            
Same as above
            const int const x = 10; 
            
This is nonsense. Pointers have two different kinds of const qualifiers makes sense, one is for the pointer itself, the other for what the pointer points. But it doesn't make sense for int type to have two different kinds of const qualifiers. Just use one
            foo const* p;
            
p points to a constant foo. The foo object can't be changed. It means p points to an object of class foo, but p can't be used to change that foo object (naturally p could also be NULL). For example, if class foo has a const member function called inspect(), saying p->inspect() is OK. But if class foo has a non-const member function called mutate(), saying p->mutate() is an error
            const foo* p
            
Same as above
            foo* const p;
            
p is a const pointer to a foo. You can't change the pointer p, but you can change the foo object
            foo const* const p;
            
p is a const pointer to a const foo.You can't change the pointer p itself, neither can you change the foo object
            const foo* const p;
            
            foo const& r;
            
It means r aliases a foo object, but r can't be used to change that foo object. For example, if class foo has a const member function called inspect(), saying r.inspect() is OK. But if class foo has a non-const member function called mutate(), saying r.mutate() is an error
            const foo& r;
            
Same as above
            foo& const r;
            
This is nonsense. r is a const reference to a foo. But that is redundant, since references are always const. You can't reseat a reference. Never. With or without the const. In other words, "foo& const r" is functionally equivalent to "foo& x". Since you're gaining nothing by adding the const after the &, you shouldn't add it since it will confuse people — the const will make some people think that the foo is const, as if you had said "foo const& x".
            int GetValue() const;
            
This member function cannot change this pointer, i.e. the class members of this pointer. It can however change any other
            const foo GetValue();
            
            const int& GetValue();
            
Returns a const reference to the member variable if it's a getter method. This won't make copies and return.
            int* GetValue();
            
            const int* GetValue();
            
            const int GetValue() const;
            
            const int& GetValue() const;
            
            int* GetValue() const;
            
            const int* GetValue() const;
            

Note: const class objects can only call const member functions

Three ways you can initialize a const member variable.
1. Inside the class declaration
static const int x = 10;
2. Outside the class
class A
{
   static const int a;
};

const int A::a = 10;    //defining the static member outside the class
Note: static means there is a single copy of the variable for all instances of the object, constant or not. It creates just one copy of it for all the objects. It is a design choice that needs to be considered carefully.
3. In constructor initialization list
class A
{
  const int b;
  A(int c):b(c){}    //const member initialized in initialization list
};

Note: "mutable" keyword is used with member variables which we want to be able to change even on const class objects. Hence, mutable data members of const objects can be modified
class A
{
    int x;
    mutable int y;
    public:
    A()
    {
        x = 0;
        y = 0;
    }
    void func() const
    { 
        i++;  // Error, cannot modify 
        j++;  // Works, because y is mutable
    }
    void func()
    { 
        i++;  // Error, cannot modify 
        j++;  // Works, because y is mutable
    }
};

int main()
{
    const A constObj;
    constObj.func();    // Calls the const func method, since constObj is const object

    A obj;
    obj.func();         // Call the non const func method, since obj is non const object
}

C++ Reference Vs Pointer

Reference Pointer
A reference is a variable that refers to something else and can be used as an alias for that something else. A reference is the object. A reference can be thought of as a constant pointer (not to be confused with a pointer to a constant value!) with automatic indirection, i.e. the compiler will apply the * operator for you. A pointer is a variable that stores a memory address, for the purpose of acting as an alias to what is stored at that address.
Const references can be bound to temporaries. This makes const& safer for use in argument lists and so forth. Pointers cannot (not without some indirection).
    const int &x = int(12);     // legal C++
    int *y = &int(12);          // illegal to dereference 
                                // a temporary.
    
A reference cannot be reassigned, and must be assigned at initialization. A reference can not be re-seated/reassigned after binding. A reference, always refers to the object with which it is initialized A pointer can be re-assigned any number of times.
    int x = 5;
    int y = 6;
    int *p;
    p = &x;     // p points to x
    p = &y;     // p now points to y
    *p = 10;    // p now is 10

    // Another special example

    string s1("Nancy");  
    string s2("Clancy");  
    string& rs = s1;    // rs refers to s1  
  
    string *ps = &s1;   // ps points to s1 
  
    rs = s2;    // rs still refers to s1,  
                // but s1's value is now "Clancy", 
                // as if s1 = s2  
  
    ps = &s2;   // ps now points to s2;  
                // s1 is unchanged   
    
References always refer to an object. Because a reference must refer to an object, C++ requires that references be initialized
    string& rs;         // error! References must  
                        // be initialized  
    string s("xyzzy");  
    string& rs = s;     // okay, rs refers to s  
    int &r = NULL;      //<--- compiling error 
    
Pointers can point to nowhere (NULL).
    string *ps;     // uninitialized pointer
                    // Its valid but risky  
    int *p = NULL;
    
The fact that there is no such thing as a null reference implies that it can be more efficient to use references than to use pointers. That's because there's no need to test the validity of a reference before using it
    void printDouble(const double& rd)  
    {  
        cout << rd; // no need to test rd; it  
    } 
    
Pointers, on the other hand, should generally be tested against null.
    void printDouble(const double *pd)  
    {  
        if (pd) // check for null pointer
        {               
            cout << *pd;  
        }  
    } 
    
You can't test if a reference is NULL.
    if(&ref == NULL)    // Not possible
    
You can test if a pointer is NULL.
    if(*ptr == NULL)    // Possible
    
References only offer one level of indirection. You can have pointers to pointers to pointers offering extra levels of indirection.
You can't take the address of a reference. You can take the address of a pointer.
There's no "reference arithmetics" (but you can take the address of an object pointed by a reference and do pointer arithmetics on it e.g. &obj + 5). You can perform arithmetics with pointers, like post increment, pre increment. Pointers can iterate over an array, you can use ++ to go to the next item that a pointer is pointing to, and + 4 to go to the 5th element. This is no matter what size the object is that the pointer points to.
Regardless of how a reference is implemented, a reference has the same memory address as the item it references. A pointer is a variable that holds a memory address.
References cannot be stuffed into an array. Pointers can be stuffed into an array.
A reference can be used directly. A pointer needs to be dereferenced with * to access the memory location it points to.
A reference to a class/struct uses . to access its members. A pointer to a class/struct uses -> to access its members.
There is one other situation in which you should use a reference, and that's when you're implementing certain operators. The most common example is operator[]. This operator typically needs to return something than can be used as the target of an assignment.
    vector <int> v(10);  // create an int vector of size 10;
    v[5] = 10;          // the target of this assignment
                        // is the return value of operator[]
    
If operator[] returned a pointer, this last statement would have to be written this way:
    *v[5] = 10;
    
But this makes it look like v is a vector of pointers, which it's not. For this reason, you'll almost always want operator[] to return a reference.
 

As a general rule,
Use references in function parameters and return types to define useful and self-documenting interfaces.
Use pointers to implement algorithms and data structures.