Showing posts with label Cplusplus. Show all posts
Showing posts with label Cplusplus. Show all posts

Wednesday, March 02, 2016

Static

Static keyword

1) static variables
2) static methods
3) static blocks of code.

static variable

  • It is a variable which belongs to the class and not to object(instance)
  • Static variables are initialized only once , at the start of the execution . These variables will be initialized first, before the initialization of any instance variables
  • A single copy to be shared by all instances of the class
  • A static variable can be accessed directly by the class name and doesn’t need any object
  • Syntax : <class-name>.<variable-name>
class Book {
    public static String Title;
    public static String Author;
    int yearPublished;
}

public class StaticMain2 {
    public static void main(String[] args) { //no need an instance of class
                                             //otherwise Book b = new Book();
                                             // to access b.yearPublished
        Book.Title = "Psychology and Human Evolution";
        Book.Author = "Jeannot Lamm";
           
    }
}

         static method

  • It is a method which belongs to the class and not to the object(instance)
  • A static method can access only static data. It can not access non-static data (instance variables)
  • A static method can  call only  other static methods and can not call a non-static method from it.
  • A static method  can be accessed directly by the class name and doesn’t need any object
  • Syntax : <class-name>.<method-name>
  • A static method cannot refer to "this" or "super"  keywords in anyway

          static block

           The static block, is a block of statement inside a Java class that will be executed when a class is first loaded in to the JVM

          class Test{
           static {
           //Code goes here
          }
           }
 
public static void main(String[] args){
  Thread t1 = new Thread(new Runnable() {
...
private static void producer(){  //static function in a class since no object (new) defined static
  Random random = new Random();
  while(true){
   try {
//    Integer val = random.nextInt(100);
    queue.put(random.nextInt(100)); //range 0 - 99
   } catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
  }
 }
Static initialize block is executed even before JVM calls main method. They are executed when a Class is loaded into Memory by JVM.

In C/C++:
- A static variable, declared globally, will only be visible in that source file. Static functions are functions that are only visible to other functions in the same file. Global all files can access it using C keyword extern.

 static int varl //can't be seen from outside files, limit the scope.
 int var;          //Variables that are defined outside functions - global variables. Can see from outside
- The variable is permanent. The variable can only be initialized once and only one copy of the variable exists.(initialized at compilation time), retains it value between calls.
-Only one copy if the variable exits. All instances of the object use the same variables
-Static Function can only access static members/fields of the class but non-static member function can access static member function or data(see example below) and it can call only other static member functions. Normally, the address of the current object(this) is passed in when any member function is called, but a static member has no "this" which is the reason it cannot access ordinary members a bit faster since doesn't have (this). At the same time you get the benefits of having the function inside the class (p.473 of Thinking of C++ Bruce Eckel.). Static members have the same properties as global variables but enjoying class scope. It is a global variables, the only difference is its name outside the class. Static data members of a class are also known as "class variables" is a variable defined in a class of which a single copy exists, regardless of how many instances of the class exist. It does not depend on any object. There is only one unique value for all the objects of that same class. For the above reasons main in Java has a static keyword.
          public static void main(String args[])
The keyword static allows main() to be called without having to instantiate a particular instance of the class. This is necessary since main() is called by the Java interpreter before any objects are made. Before the main method is called, no objects are instantiated. Having the static keyword means the method can be called without creating any objects first. The main() method in C++, C# and Java are static because they can then be invoked by the runtime engine without having to instantiate an instance of the parent class. Now main without keyword static.
          public void main(String args[])
Exception in thread "main" java.lang.NoSuchMethodError: main (cannot find main because no object is initiated for main)
Since main method is static Java virtual Machine can call it without creating any instance of class which contains main method. Otherwise JVM has to create instance of main Class and since constructor main() can be overloaded and can have arguments there would not be any certain and consistent way for JVM to find main method in Java. All objects of non-primitive types can be created only via "new" in Java. There is no equivalent to creating non-primitive objects on the stack as in C++. Anything which is declared in class in Java comes under reference type and requires object to be created before using them but static method and static data are loaded into separate memory inside JVM called context which is created when a class is loaded. If main method is static than it will be loaded in JVM context and are available to execution.
-Static will remain reserved for the duration of the execution program. Consider this bit of code.
 char *func(void);

        main()
        {
            char *Text1;
            Text1 = func();
        }

        char *func(void)
        {
            char Text2[10]="martin";
            return(Text2);
        }

 Now, 'func' returns a pointer to the memory location where 'text2' starts BUT text2 has a storage class of 'auto' and will disappear when we exit the function and could be overwritten but something else. The answer is to specify
        static char Text[10]="martin";


class Student {
        int a; //initialized to zero
        static int b; //initialized to zero only when class is loaded not for each object created.

          Student(){
           //Constructor incrementing static variable b
           b++;
          }


           public void showData(){
              System.out.println("Value of a = "+a);
              System.out.println("Value of b = "+b);
           }
        //public static void increment(){
        //a++;
        //}

        }

        class Demo{
           public static void main(String args[]){
             Student s1 = new Student();
             s1.showData();
             Student s2 = new Student();
             s2.showData();
        //     Student.a++;  //cannot access instance variable "a" from static method "increment"
        //     s1.showData();
          }
        }
//: C10:StaticMemberFunctions.cpp
class X {
int i;
static int j;
public:
 X(int ii = 0) : i(ii) {
 // Non-static member function can access
 // static member function or data:
 j = i;
 }
 int val() const { return i; }
 static int incr() {
 //! i++; // Error: static member function
 // cannot access non-static member data
 return ++j;
 }
 static int f() {
 //! val(); // Error: static member function
 // cannot access non-static member function
 return incr(); // OK -- calls static
 int v;
 }
};
int X::j = 0;  // a static for all objects it works
//int X::i = 1;  // error: ‘int X::i’ is not a static member of ‘class X’

int main() {
 X x;
 X* xp = &x;
 x.f();
 xp->f();
 X::f(); // with static Only works with static members. error: cannot call member function ‘int X::f()’ without object
 x.f();  // without static need an object
// int X::j = 0;
} ///:~

C++ Static Class: C++ doesn't directly support a static class only Static data members and Static member functions. There is no "static class" in C++. The nearest concept would be a class with only static methods


See http://stackoverflow.com/questions/1303947/c-compiler-warning-returning-local-variable/35777878#35777878
class Three
{
    string *m_ob;
    int m_x, m_y, m_z;
public:
    Three(){}
    Three(string ob, int x, int y, int z): m_ob(new string(ob)), m_x(x), m_y(y), m_z(z) {}
    Three &operator+(Three &t)
    {
        static Three th;  //static here otherwise return this object is gone!
        th.m_ob = new string("Sum object");
        cout << "---------" << this->m_x << " " << t.m_x << endl;
        th.m_x = this->m_x + t.m_x;
        th.m_y = this->m_y + t.m_y;
        th.m_z = this->m_z + t.m_z;
        return th; //create in stack gone when return
    }

    friend ostream &operator<< (ostream &stream, Three t)
    {
        stream << *t.m_ob <<": ",
        stream << t.m_x << ",";
        stream << t.m_y << ",";
        stream << t.m_z << "\n";
        return stream;
    }
};

int main()
{
    Three ob1("ob1", 1, 2, 3), ob2("ob2", 4, 5, 6), ob3("ob3", 7, 8, 9);
    cout << ob1 << ob2 << ob3 << endl;
    Three ob = ob1 + ob2 + ob3;
    cout << ob << endl;
}
//Without static Three th will error: warning: reference to local variable ‘th’ returned [-Wreturn-local-addr]
//object create in stack it is gone when return. In c_cpp_reference when return value need static.

Inline functions versus Macros

 Although inline functions are similar to macros (because the function code is expanded at the point of the call at compile time), inline functions are parsed by the compiler, whereas macros are expanded by the preprocessor. As a result, there are several important differences:
  1.  Inline functions follow all the protocols of type safety enforced on normal functions.
  2.  Inline functions are specified using the same syntax as any other function except that they include the inline keyword in the function declaration.
  3.  Expressions passed as arguments to inline functions are evaluated once. In some cases, expressions passed as arguments to macros can be evaluated more than once.

    // inline_functions_macro.c
    
        #include <stdio.h>
        #include <conio.h>
    
        #define toupper(a) ((a) >= 'a' && ((a) <= 'z') ? ((a)-('a'-'A')):(a))
    
        int main() {
           char ch;
           printf_s("Enter a character: ");
           ch = toupper( getc(stdin) );
           printf_s( "%c", ch );
        }
    
        Input
    
        xyz
    
        Inline functions remedy the problem previously described.
    
        // inline_functions_inline.cpp
        #include <stdio.h>
        #include <conio.h>
    
        inline char toupper( char a ) {
           return ((a >= 'a' && a <= 'z') ? a-('a'-'A') : a );
        }
    
        int main() {
           printf_s("Enter a character: ");
           char ch = toupper( getc(stdin) );
           printf_s( "%c", ch );
        }
    
        Input
    
        a
    
        Output
    
        Enter a character: A

String, StringBuffer and StringBuilder in Java


Differences between String and StringBuffer in Java
Main difference between String and StringBuffer is String is immutable while StringBuffer is mutable means you can modify a StringBuffer object once you created it without creating any new object. This mutable property makes StringBuffer an ideal choice for dealing with Strings in Java. You can convert a StringBuffer into String by its toString() method. String vs StringBuffer or what is difference between StringBuffer and String is one of the popular interview questions for either phone interview or first round. Now days they also include StringBuilder and ask String vs StringBuffer vs StringBuilder. So be preparing for that. In the next section we will see difference between StringBuffer and StringBuilder in Java.
Difference between StringBuilder and StringBuffer in Java
StringBuffer is very good with mutable String but it has one disadvantage all its public methods are synchronized which makes it thread-safe but same time slow. In JDK 5 they provided similar class called StringBuilder in Java which is a copy of StringBuffer but without synchronization. Try to use StringBuilder whenever possible it performs better in most of cases than StringBuffer class. You can also use "+" for concatenating two string because "+" operation is internal implemented using either StringBuffer or StringBuilder in Java. If you see StringBuilder vs StringBuffer you will find that they are exactly similar and all API methods applicable to StringBuffer are also applicable to StringBuilder in Java. On the other hand String vs StringBuffer is completely different and there API is also completely different, same is true for StringBuilders vs String.


Java provides the StringBuffer and String classes, and the String class is used to manipulate character strings that cannot be changed. Simply stated, objects of type String are read only and immutable. The StringBuffer class is used to represent characters that can be modified.

The significant performance difference between these two classes is that StringBuffer is faster than String when performing simple concatenations. In String manipulation code, character strings are routinely concatenated. Using the String class, concatenations are typically performed as follows:
String str = new String ("Stanford ");
str += "Lost!!";
If you were to use StringBuffer to perform the same concatenation, you would need code that looks like this:
StringBuffer str = new StringBuffer ("Stanford ");
str.append("Lost!!"
More...
String s = "a" + "b" + "c";
It is rather pointless to use StringBuffer.
String s = new StringBuffer().append("a").append("b").append("c").toString();
String s = "";
for (int i = 0; i < 10; i++) {
s = s + Integer.toString(i);
}


Using string in this loop will generate 10 intermediate string objects in memory: "0", "01", "012" and so on. While writing the same using StringBuffer you simply update some internal buffer of StringBuffer and you do not create those intermediate string objects that you do not need:


StringBuffer sb = new StringBuffer();
for (int i = 0; i < 10; i++) {
sb.append(i);
}
Actually for the example above you should use StringBuilder (introduced in Java 1.5) instead of StringBuffer - StringBuffer is little heavier as all its methods are synchronized.

Summary:

In Java, String concatenation operator (+) is internally implemented using StringBuffer.
String str = "Hello" + "World";
Would be executed as,
Concatenation operator "+" is internal implemented using either StringBuffer or StringBuilder.
String str = new StringBuffer().append("Hello").append("World").toString();
First an empty StringBuffer will be created and then operands of the + operator would be appended using append method of the StringBuffer.
Finally toString() method of the StringBuffer would be called to convert it to string object and the same will be returned.
String concatenation using this approach is very expensive in nature, because it involves creation of temporary StringBuffer object. Then that temporary object’s append method gets called and the resulting StringBuffer should be converted to back String representation using toString() method.
When to use String and when StringBuffer?
If there is a need to change the contents frequently, StringBuffer should be used instead of String because StringBuffer concatenation is significantly faster than String concatenation
String is immutable while StringBuffer and StringBuilder is mutable object
When to use StringBuffer and when StringBuilder
StringBuffer is synchronized while StringBuilder is not which makes StringBuilder faster than StringBuffer.
Use String if you require immutability, use Stringbuffer in java if you need mutable + threadsafety and use StringBuilder in Java if you require mutable + without thread-safety
Ref:
http://javarevisited.blogspot.ca/2011/07/string-vs-stringbuffer-vs-stringbuilder.html http://www.javaworld.com/javaworld/jw-03-2000/jw-0324-javaperf.html

Const vs. Final

In Java const is just a reserve keyword, there is no const in Java. But it can be done similar to const in C++. You can create a constant variable in a class. To create a constant variable, type the final keyword to the left of the variable. Once again, when declaring a constant, you must initialize it with an appropriate constant value. static final in MAX_UNITS = 25; in C++ const MAX_UNITS = 25; A final variable in Java can be assigned to only once, but if the variable is a reference-type, you can still change what it refers to. A const variable in C++ can be assigned to only once, where it’s declared, and nothing is allowed to change about the value, whether it’s an object or not.

this Instance

If a class contains member variables and methods, the (non-static) member variables are automatically available to the method(s) of the class, even member variables that are private. When accessing a member variable or a method from another method of the class, to indicate that the member you are accessing belongs to the same class, you can precede it with the this member and the period operator.

C++ vs. Java

  1. C less rules than C++, C++ is less rules than Java. Java many things you don't have to worry but many rules have to follow.
  2. By default, all members of a class are private and all the members of structure are public in C++ and by default, all the members of a Java class are public. This means that if you do not use the public or the private keyword, a field is automatically made by default scope. (access specifiers to use specify the scope of members of the class and the class itself). If the class has no specifier by default then such a class will be accessible from inside the same package. The class can either public or no specifier.
    public or no modifier - the same way as used in the class level
    private - members can only access
    protected -can be accessed from the same package and a subclass existing in any package can access.
  3. Java has char type uses the international 16-bit Unicode, C++ has char type 1 byte for 32-bit system and 2 bytes for 64-bit system.
  4. C-language did not contain any data types to represent a Boolean value. Both the C++ and Java languages have Boolean types.
    C++
    bool foo;
    Java
    boolean foo;
     
    
    
  5. Pointers
    The Java language does not include pointers. The reason for this is simple: pointers tend to cause confusion in the code, and they are a common source of bugs. Java references are pointers to Java objects, but you can't use Java references in the same way that you can use C pointers. Java references cannot be incremented or decremented, you can't convert references to or from primitive types, and there are no address of operators, such as &, or dereferencing operators, such as -> or *.
  6. Global variables: Unlike C and C++, the Java language offers no way to declare global variables (or methods).
  7. The preprocessor: The Java platform does not have a preprocessor, nor does it have any preprocessor directives or macros.
  8. goto: Although the Java language reserves goto as a keyword, there is no goto statement like the one used in C.
  9. struct, union, typedef, enum: The Java language does not have the struct or union types, nor does it have the typedef or enum keywords.
  10.  Freely placed variables: Java variables can be declared anywhere, as they are needed. Variables do not need to be grouped together at the top of a block, as they do in C.
  11. Freely placed methods: C requires that function declarations appear before they are invoked, but Java methods can be invoked before they have been declared.
  12. Garbage collection: The Java platform uses a garbage collector to
    automatically reclaim memory by recycling objects when they are no
    longer referenced. The malloc() and free() functions used by C
    aren't necessary in Java programming, and no similar methods exist for
    the Java language.
  13. No difference between Access Modifiers and Access Specifiers. Different names for the same.
    Access modifiers: abstract, final and strictfp . Access specifier: public,private, protected or default. 
    Java access Specifier are used to specify how the member variable ,methods or class to other classes.
    They are public ,private and protected.
    
    Access Modifier:
       1.Access
       2.Non Access
    
    Access:
        public ,private,protected and default.
    Non Access:
     abstract,final,native,static,synchronized,transient,volatile
     and strictfp
     
  14. What's the difference between an interface and an abstract class?
    • An abstract class is a class that is only partially implemented by the programmer. It may contain one or more abstract methods. An abstract method is simply a function definition that serves to tell the programmer that the method must be implemented in a child class.
    • An interface is similar to an abstract class; indeed interfaces occupy the same namespace as classes and abstract classes. For that reason, you cannot define an interface with the same name as a class. An interface is a fully abstract class; none of its methods are implemented and instead of a class sub-classing from it, it is said to implement that interface.
    • Abstract classes can have constants, members, method stubs and defined methods, whereas interfaces can only have constants and methods stubs.
    • Methods and members of an abstract class can be defined with any visibility, whereas all methods of an interface must be defined as public.
    • When inheriting an abstract class, the child class must define the abstract methods, whereas an interface can extend another interface and methods don't have to be defined.
    • A child class can only extend a single abstract (or any other) class, whereas an interface can extend or a class can implement multiple other interfaces.
    • A child class can define abstract methods with the same or less restrictive visibility, whereas a class implementing an interface must define the methods with the exact same visibility 
  15. When to use abstract class or interface?
    • Interface is used when you only want to declare which methods and members a class MUST have. Anyone implementing the interfaca will have to declare and implement the methods listed by the interface.
    • If you also want to have a default implementation, use abstract class. Any class extending the abstract class will have to implement only its abstract methods and members, and will have some default implementation of the other methods of the abstract class, which you may override or not.
    • Finally, you can implement as many interfaces as you want, but only extend one class (being it abstract or not). Keep that on mind before choosing.
    • public class C implements A, B{... }
    • public class C extends A{...}
    • Abstract class is an incomplete implementation of some concept. This incomplete implementation may be different in different context. Derived class implements the abstract class in its context.
    • Interface defines contract or standard. Implementation of the interface has to follow the contract or standard. Interfaces are more used to set these types of standards or contract
  16.  What does the Serializable interface do ?
    • The Serializable interface is just a marker. It means that objects can be serialized, i.e. they can be represented as a bit string and restored from that bit string. For example, both of your classes are serializable because they can be represented as a bit string (or regular string). On the other hand, a class that represents a file handle given out by the operating system can not be serialized: As soon as the program is finished, that handle is gone, and there is no way to get it back. Reopening the file by file name is not guaranteed to work, since it may have been deleted/moved/changed permissions in the meantime.
    • Serializing objects that don't implement the Serializable interface will result in a NotSerializableException being thrown
  17. How you can force the garbage collection ?
    • Garbage collection automatic process and can't be forced. You could request it by calling System.gc(). JVM does not guarantee that GC will be started immediately.
    • Garbage collection is one of the most important feature of Java, Garbage collection is also called automatic memory management as JVM automatically removes the unused variables/objects (value is null) from the memory. User program can't directly free the object from memory, instead it is the job of the garbage collector to automatically free the objects that are no longer referenced by a program.
    •  Every class inherits finalize() method from java.lang.Object, the finalize() method is called by garbage collector when it determines no more references to the object exists. In Java, it is good idea to explicitly assign null into a variable when no more in use. I Java on calling System.gc() and Runtime.gc(), JVM tries to recycle the unused objects, but there is no guarantee when all the objects will garbage collected.
  18. What is Synchronization in Java?
    • Synchronization is a process of controlling the access of shared resources by the multiple threads in such a manner that only one thread can access one resource at a time.
    •  In non synchronized multithreaded application, it is possible for one thread to modify a shared object while another thread is in the process of using or updating the object's value.
  19. What is memory leak?
    • A memory leak is where an unreferenced object that will never be used again still hangs around in memory and doesnt get garbage collected.
  20.  What is the difference between checked and unchecked exceptions?
    • In general, unchecked exceptions represent defects in the program (bugs), which are normally Runtime exceptions.
    •  Furthermore, checked exceptions represent invalid conditions in areas outside the immediate control of the program.
  21.  How does Java allocate stack and heap memory?
    •  Each time an object is created in Java it goes into the area of memory known as heap. The primitive variables like int and double are allocated in the stack, if they are local method variables and in the heap if they are member variables (i.e. fields of a class).
    • In Java methods local variables are pushed into stack when a method is invoked and stack pointer is decremented when a method call is completed.
    •  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.
    •  The stack is threadsafe (each thread will have its own stack) but the heap is not threadsafe unless guarded with synchronisation through your code
  22. What is Java Reflection?
    • Reflection is commonly used by programs which require the ability to examine or modify the runtime behavior of applications running in the Java virtual machine.

    Tuesday, July 03, 2012

    Why default constructor is required(explicitly) in a parent class if it has an argumented constructor

    class A {    
      A(int i){    
      }
    }
    class B extends A {
    }
    class Main {    
      public static void main(String a[]){
        B b_obj = new B();
      }
    }
    
    This will be an error: cannot find symbol constructor in B If we don't have argument constructor the compiler will insert super() the first line in derived class constructor. Since the parent has parameter(arguments) constructor, it supersedes the default constructor in A, the compiler could not find the default constructor per error showing therefore so we need to insert the default constructor.
    So class A will have 2 constructors: default A(){} and A(int i){}.
    2 ways to fix it
    - has a default constructor in parent class A
    - has a super(int) in B constructor
    class A {    
      A(int i){    
      }
    
      A(){}     //insert the default constructor in the base class, derived class unchanged 
    }
    class B extends A {
    }
    class Main {    
      public static void main(String a[]){
        B b_obj = new B();
      }
    }
     
    
    class A {    
      A(int i){    
      } 
    }
    class B extends A {
    
      B(int i) {    // add constructor for B with super(i) in the 1st line
    
      super(i); 
    
      }
    }
    class Main {    
      public static void main(String a[]){
        B b_obj = new B(2); //constructor has a value
      }
    }
    
    Same thing in C++ you need to create a default constructor for base class if the base class has arguments constructor as long as this argument/parameter constructor is exist the compile will not create default constructor. In Java you can use "super" keyword to call parameter constructor is must be the first line of derived/child constructor. To be compatible for both C++ and Java it is always good to have the parent default constructor.
    class A { 
     int i;
      public:  
      A(){}  
      A(int i){}   //A(int i) no default constructor you have to create one above A(){} like Java
    };
    class B : public A {
      public:
    };
    
    int  main(){
       B *b_obj = new B;  // for B compiler will use default constructor B(){} requires A(){}
    }
    
    See this for the full behaviors of C++ WRT constructors: http://en.wikipedia.org/wiki/Default_constructor
    if you specify a constructor, the compiler will not create a default one for you. The compiler will define a default ctor if and only if you don't explicitly declare any ctors. It is confusing when there is a parent and child class (derived class). In the above examples, we think that the compiler will generate the default constructor for the child class since there is no constructor is defined so it creates a default constructor for the child but when the object is created in the child class, the parent constructor is called first then the child constructor, this is where the error happens because it could not find the default constructor in the parent class.
    This rule applies to Java and C++ as well.
    Another way to do is let the child class initializes the base class ctor then no default ctor at base class as long as the compiler know there is one ctor is defined so it does not look for a default ctor. This is the case there is no source code for base class just a library to link and it can be set in the derived class (child class)
    #include <iostream>
    using namespace std;
    
    class A { 
     int i;
      public:  
      //A(){}  
      A(int i){}   //A(int i) no default constructor you have to create one above A(){} like Java
    };
    class B : public A {
     public:
     int j;
     B():A(j){}   // derived class initialize the base class constructor
    };
    
    int  main(){
       B *b_obj = new B;
    }
    

    Wednesday, June 27, 2012

    Templates

    A generic function defines a general set of operations that will be applied to various types of data. For example using template to swap a float, int or char.

    Function Template:

    // Function template example. p.751 BorlandC
    #include <iostream>
    using namespace std;
    // This is a function template.
    //void swapargs(int &a, int &b)
    //{
    ////X temp;
    //int temp = a;
    //a = b;
    //b = temp;
    //}
    //void swapargs(float &a, float &b)
    //{
    ////X temp;
    //int temp = a;
    //a = b;
    //b = temp;
    //}
    //void swapargs(char &a, char &b)
    //{
    ////X temp;
    //int temp = a;
    //a = b;
    //b = temp;
    //}
    template <class X> 
    void swapargs(X &a, X &b)
    {
    X temp;
    temp = a;
    a = b;
    b = temp;
    }
    
    int main()
    {
    int i=10, j=20;
    float x=10.1, y=23.3;
    char a='x', b='z';
    cout << "Original i, j: " << i << ' ' << j << endl;
    cout << "Original x, y: " << x << ' ' << y << endl;
    cout << "Original a, b: " << a << ' ' << b << endl;
    swapargs(i, j); // swap integers
    swapargs(x, y); // swap floats
    swapargs(a, b); // swap chars
    cout << "Swapped i, j: " << i << ' ' << j << endl;
    cout << "Swapped x, y: " << x << ' ' << y << endl;
    cout << "Swapped a, b: " << a << ' ' << b << endl;
    return 0;
    }
    
    
    Output:
    Original i, j: 10 20
    Original x, y: 10.1 23.3
    Original a, b: x z
    Swapped i, j: 20 10
    Swapped x, y: 23.3 10.1
    Swapped a, b: z x

    Class Template:

    // class templates
    #include <iostream>
    using namespace std;
    
    template <class T>
    class mypair {
        T a, b;
      public:
        mypair (T first, T second)
          {a=first; b=second;}
        T getmax ();
    };
    
    template <class T>
    T mypair<T>::getmax ()
    {
      T retval;
      retval = a>b? a : b;
      return retval;
    }
    
    int main () {
      mypair <int> myobject (100, 75);
      cout << myobject.getmax();
      return 0;
    }
    

    Saturday, June 16, 2012

    Const and Reference

    Const, Pointer and Reference in C/C++ Passing by reference or pointer in doubleit resulting the values in main will be altered
    //in C no reference using pointers changes the value of memory location resulting altering the values in main
    #include <stdio.h>
     
    void doubleit( int *x, int *y){
       *x *= 2;
       *y *= 2;
    }
     
    int main(void){
       int x = 10;
       int y = 5;
       doubleit( &x, &y);
       printf("%i %i",x,y);
       return 0;
    }
    //C++ using references change the value of memory location resulting altering the values in main
    #include <stdio.h>
     
    void doubleit( int &x, int &y){
       x *= 2;
       y *= 2;
    }
     
    int main(void){
       int x = 10;
       int y = 5;
       doubleit( x, y);
       printf("%i %i",x,y);
       return 0;
    }
    //C/C++ passing by values the values in main will not change, it makes a copy x, y for doubleit and it will be destroyed when function is returned
    #include <stdio.h>
     
    void doubleit( int x, int y){
       x *= 2;
       y *= 2;
    }
     
    int main(void){
       int x = 10;
       int y = 5;
       doubleit( x, y);
       printf("%i %i",x,y);
       return 0;
    }
    //Const, Reference and values
    #include <stdio.h>
     
     
    //void doubleit(int x, int y){  //unchange the values x, y in main copy varibles and keep the original in main
    //void doubleit(int &x, int &y){  //change values x, y in main by reference 
    void doubleit(const int &x, const int &y){ // unchange the values x, y in main by const compile will check if it is altered can read only
    // which will cause variable to be passed by reference without copying but stop it from being altered.
    //x *= 2;
    //y *= 2;
     int i = x*2;
     int j = y*2;
     printf("%i %i\n",x,y);
    }
     
    int main(void){
     int x = 10;
     int y = 5;
      
     doubleit(x,y);
      
     printf("%i %i",x,y);
    
      
     return 0;
    }
    
    Even more useful is a pointer (constant or otherwise) to a ‘const’ value. This is useful for returning constant strings and arrays from functions which, because they are implemented as pointers, the program could otherwise try to alter and crash. Instead of a difficult to track down crash, the attempt to alter unalterable values will be detected during compilation. For example, if a function which returns a fixed ‘Some text’ string is written like char *Function1() { return “Some text”;} then the program could crash if it accidentally tried to alter the value doing Function1()[1]=’a’; whereas the compiler would have spotted the error if the original function had been written const char *Function1() { return "Some text";} because the compiler would then know that the value was unalterable. (Of course, the compiler could theoretically have worked that out anyway but C is not that clever. Passing an object by reference.
    // C++
    class Type; // defined somewhere before, with the appropriate operations
    void swap( Type & a, Type & b ) {  //like variables need & for function
       Type tmp = a;
       a = b;
       b = tmp;
    }
    int main() {
       Type a, b;
       Type old_a = a, old_b = b;
       swap( a, b );    //like in the previous example for variables just the name
       assert( a == old_b );
       assert( b == old_a ); 
    }
    
    The swap function above changes both its arguments through the use of references. The closest code in Java:
    //Java
    public class C {
       // ...
       public static void swap( C a, C b ) {
          C tmp = a;
          a = b;
          b = tmp;
       }
       public static void main( String args[] ) {
          C a = new C();
          C b = new C();
          C old_a = a;
          C old_b = b;
          swap( a, b ); 
          // a and b remain unchanged a==old_a, and b==old_b
       }
    }
    
    The Java version of the code will modify the copies of the references internally, but will not modify the actual objects externally. Java references are C pointers without pointer arithmetic that get passed by value into functions. Can I access private members from outside the class without using friends in C++? Yes, you can Conceptually in C/C++
    #include <iostream>
    #include <string>
    using namespace std;
    int main(){
     int i = 2;
     int *j = &i; //j and i are the same in memory location
     *j = 4;  // change value of i because the same memory location for i and j
     cout << i << endl;
    return 0;
    
    AccessMemoryOfPrivateUseFriend.cpp: In function ‘Student Show(std::string, int)’:
    AccessMemoryOfPrivateUseFriend.cpp:7: error: ‘std::string Student::name’ is private
    Therefore we need a friend keyword function like this.
    #include <iostream>
    #include <string>
    using namespace std;
    
    class Student {
         private:
           string name;
           int grade;
         public:
           void ShowStudent() { cout << name << " " << grade << endl;}
           friend Student Show(string, int); //friend function to access class private
     };
    Student Show(string s, int y)
    {
       Student T;
       T.name = s;
       T.grade = y;
       return T;
    }
    
    int main(){
      Student S;
      S = Show("Tom", 10);
      S.ShowStudent();
      return 0;
     }
    Output: Tom 10
    Without Friend we can do as with the above for integer. 
    Create another class with the same layout as the object with private members but with private changed to public. Create a variable of pointer to this class. Use a simple cast to point this to your object with private members and try calling a private function.
    #include <iostream>
    #include <string>
    using namespace std;
    
    class Student {
         private:
         string name;
         int grade;
      public:
         void ShowStudent() { cout << name << " " << grade << endl;}
     };
    class Me {
     public: 
      string myname;
      int mygrade;
    }; 
    int main(){
      Student T;
      Me *p;
      p = (Me*)&T;
      p->myname = "Tom";
      p->mygrade = 10;
      T.ShowStudent();
      return 0;
     }
    Output: Tom 10 (we get the same output as friend function before without using friend)
    
    Using template to access private members of the class.
    #include <iostream>
    using namespace std;
    class safe
    {
        int money;
    
    public:
        safe() : money(1000000){ cout << "Constructor is called initializes 1000000" << endl;}
    
        template <typename T> //template
        void backdoor()
        {
         money -= 50000;
         cout << "Template "<< money << endl;
        }
        //void take(){ safe T; T.money -= 1; cout << T.money << endl;}
        friend void take(safe);
    };
    void take(safe T) { T.money -= 1; cout << "Friend " << T.money << endl;}
    
    //class me;
    //class key;
    
    template <> //template specialization
    void safe::backdoor<class key>()  //void safe::backdoor<class key>()
    {
        // My specialization.
        money -= 100000;
        cout << "Template specialization " << money << "\n";
    }
    
    int main()
    {
        safe s;
        s.backdoor<class key>();
        s.backdoor<key>();
        s.backdoor<int>();
        take(s); //error: ‘class safe’ has no member named ‘take’ just a friend not a member
    }
    
    
    Output: Constructor is called initializes 1000000 Template specialization 900000 Template specialization 800000 Template 750000 Friend 749999 In case of class Student before, using template specialization(empty template <>) can modify the private data members using template function is not compiled until an instantiation with specific template arguments is required.
    #include <iostream>
    #include <string>
    using namespace std;
    
    class Student {
         private:
         string name;
         int grade;
      public:
         void ShowStudent() { cout << name << " " << grade << endl;}
      template <typename T> //template
         void change(){ name = "Thomas"; grade = 9;}
     };
    template <>  //template specialization
    void Student::change<class modify>()  //void safe::backdoor<class key>()
    {
        // My specialization.
        name = "Hacker";
        grade = 10;
        cout << "Template specialization " << "\n";
    }
    
    int main(){
      Student T;
      T.change<modify>();
      T.ShowStudent();
      T.change<int>();
      T.ShowStudent();
      return 0;
     }
    
    Output: Hacker 10 Thomas 9

    Thursday, June 07, 2012

    Function Pointer and Overloading Function Call

    http://en.wikipedia.org/wiki/Function_pointer
    Function pointers are a complex and powerful in C/C++. It runs faster the tradition function because it only passes the pointer. They allow to pass one function as an argument to another function.
    #include <iostream>
    using namespace std;
    int myfunc(int a);
    int myfunc(int a, int b);
    int main()
    {
        int (*fp)(int a, int b);
        fp = myfunc; // points to myfunc(int)
        cout << fp(5, 2 );
        return 0;
    }
    int myfunc(int a)
        {
        return a;
        }
    int myfunc(int a, int b)
        {
        return a*b;
        }
    Using a function pointer
    Once you define a pointer to a function, you must assign it to a
    function address before you can use it. Just as the address of an
    array arr[10] is produced by the array name without the brackets
    (arr), the address of a function func() is produced by the function
    name without the argument list (func). You can also use the more
    explicit syntax &func(). To call the function, you dereference the
    pointer in the same way that you declared it (remember that C and
    C++ always try to make definitions look the same as the way they
    are used). The following example shows how a pointer to a
    function is defined and used:
    #include <iostream>

    using namespace std;
    void func() {
    cout << "func() called..." << endl;
    }
    int main() {
        void (*fp)(); // Define a function pointer
        fp = func; // Initialize it
        (*fp)(); // Dereferencing calls the function
        void (*fp2)() = func; // Define and initialize
        (*fp2)();
    }
    Overloading Function Call operator(). The function call operator when overloaded, does not modify how functions are called, it modifies how the operator is to be interpreted when applied to objects of a given type.
    struct A {
      void operator()(int a, char b, ...) { }
    //called eclipsis a variable numbers following
      void operator()(char c, int d = 20) { }
    };

    int main() {
      A a;
      a(5, 'z', 'a', 0);
      a('z');
    //  a();
    }
    ///////////////
    class Point {
    private:
      int x, y;
    public:
      Point() : x(0), y(0) { }
      Point& operator()(int dx, int dy) {
        x += dx;
        y += dy;
        return *this;
      }
    };

    int main() {
      Point pt;

      // Offset this coordinate x with 3 points
      // and coordinate y with 2 points.
      pt(3, 2);

    //////In case of Functor
    #include <iostream>
    using namespace std;
    class myFunctorClass
    {
        public:
    //        myFunctorClass (int x) : _x( x ) {cout << x << endl;}
         myFunctorClass (int x) {_x =x ; cout << x << endl;}
            int operator() (int y,...) { return _x + y; }  //Overloading Function Calls(function call operator)
        private:
            int _x;
    };

    int main()
    {
        myFunctorClass addFive( 5 );  //constructor create _x = 5
        std::cout << addFive( 6 ) << endl;
         std::cout << addFive( 6 );

        return 0;
    }


          Ref: IBM
          Cprogramming

    Explicit & Implicit

    Explicit & Implicit

    Ira Pohl Contemporary C++ style is to use access specifies explicity rather than to rely on defaults. The use of implicit features is labor saving but error prone. Therefore, it is better style to declare point as follow:  

        Class point {
        Double x, y; //implicit
        Public:
        Void print() { cout << “” << end;;
        Class point {
        Private:
        Double x, y; //explicit


    Explicit Constructors
    The keyword explicit is used to create “nonconverting constructors”. 

        class MyClass {
        int i;
        public:
        explicit MyClass(int j) {i = j;}
        // ...
        };

    Now, only constructors of the form

     MyClass ob(110);

    will be allowed.
    Otherwise if not, 

        class MyClass {
        int i;
        public:
        MyClass(int j) {i = j;}
        // ...
        };

    Class objects can be declared as shown here:

     MyClass ob1(1);
     MyClass ob2 = 10;
    In this case, the statement
     MyClass ob2 = 10;
    is automatically converted into the form
     MyClass ob2(10)

    If a method needs to refer explicitly to the object that evoked it, it
    can use the this pointer. The this pointer is set to the address of the evoking object, so *this”
    is an alias for the object itself. This is the location of object address for example.  

        class Animal {
        public String name;
        String talk(){return this.name;};
        String getName(){return name;};
        }

    Virtual Function revisited

    http://objectlayer.blogspot.ca/2006/01/what-is-virtual-function.html
    Equivalent of the interface in java for polymorphism. It is static late binding for virtual function which the derived class will override this virtual function, it is not a member of class. If append by = 0 , the object cannot instantiate only from pointer because it is a pure virtual function. The cla will be called Abstract Base Class (ABC). The pure virtual function is not defined so does the object therefore cannot create an object from ABC.
    //--C++ virtual function
    #include <iostream>
    #include <string>

    using namespace std;

    class Animal
    {
            public:
            Animal(const string& name) : name(name) {};
            virtual string talk() = 0;  //Need pure virtual function here
            //virtual string talk();
            const string name;
    };

    class Cat : public Animal
    {
            public:
            Cat(const string& name) : Animal(name) {};
            virtual string talk() { return "Meow!"; }
    };

    class Dog : public Animal
    {
            public:
            Dog(const string& name) : Animal(name) {};
            virtual string talk() { return "Arf! Arf!"; }
    };

    // prints the following:
    //
    // Missy: Meow!
    // Mr. Mistoffelees: Meow!
    // Lassie: Arf! Arf!
    //
    int main()
    {
            Animal* animals[] =           // only create pointer no object for Animal
            {
                    new Cat("Missy"),
                    new Cat("Mr. Mistoffelees"),
                    new Dog("Lassie")
            };

            for(int i = 0; i < 3; i++)
            {
                    cout << animals[i]->name << ": " << animals[i]->talk() << endl;
                    delete animals[i];
            }
            return 0;
    }

    Saturday, January 21, 2006

    C++ vs. Java

    - Java does not have pointer but instead has non primative variables that references
    - Java avoids much of the direct programmer management of memory that causes so many bugs in C and C++
    - Java does not have arrays which are references
    - Java does not have functions that are outside the scope of a class
    - Java's term for function is method
    - Multiple inheritance and concept of virtual inheritance in C++. No multiple inheritance in Java. Can get around by user interface
    - By default member of class are privates where Java a default member function/variables are visibility
    - Platform independence in Java which is not in C++
    - All member function in Java class are virtual by default, where C++ need specified
    - Constructor can be called from other constructors using this() in Java, this is not in C++

    Thursday, January 19, 2006

    What is the Virtual Function ?

    A virtual function is a member of base class that can be overridden by a derived class. If the virtual function is not overridden by the derived class, the base class definition is used.

    // virtual members
    #include
    class CPolygon {
    protected:
    int width, height;
    public:
    void set_values (int a, int b)
    { width=a; height=b; }
    virtual int area (void)
    { return (0); }
    };
    class CRectangle: public CPolygon {
    public:
    int area (void)
    { return (width * height); }
    };
    class CTriangle: public CPolygon {
    public:
    int area (void)
    { return (width * height / 2); }
    };
    int main () {
    CRectangle rect;
    CTriangle trgl;
    CPolygon poly;
    CPolygon * ppoly1 = ▭
    CPolygon * ppoly2 = &trgl;
    CPolygon * ppoly3 = &poly;
    ppoly1->set_values (4,5);
    ppoly2->set_values (4,5);
    ppoly3->set_values (4,5);
    cout <<>area() <<>area() <<>area() << endl; return 0; }
    References:
    http://people.msoe.edu/~tritt/clang.html#toc
    http://www.cplusplus.com/

    What is Polymorphism ?

    Polymorphism is the capability to bind a specific derived class object to base class pointer at run-time.

    What is Class ?

    A class is a blue-print or prototype defines the variables, functions/methods for an object.
    class class_name {
    permission_label_1:
    member1;
    permission_label_2:
    member2;
    ...
    } object_name;

    What is object ?

    An object is a software bundle of related variables and methods. Software objects are often used to model real world objects that we found in everyday life.
    A class is the blueprint from which individual objects are created.
    An object is an individual instance of a class.