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

Saturday, June 09, 2012

Modify blogger template using add custom CSS

If you google most of people try to change HTML page of the blogger by editing the HTML page and you don't have to do it any more if you know how CSS works. There is a new feature called Add CSS.
In Template -> Customize ->Advanced ->Add CSS you can customize your CSS to override the current CSS of your current template. If you want to remove the top navbar and bottom footer-3 you target the ID enter as below, if you want to expanse the background to cover the whole page target on body and body class as below. Similar when you write code in Java/C++ you can override functions of the abstract base class. It is a bit complicate to find out the target id and class you need to use the tools: firebug or web developer. You can also look at by view source of your blogger in the browser or paste into Dreamweaver to figure out those id and class for the particular CSS that needed to change. When enter into add custom CSS you can see your blog changes right away if it is correct id or class. It likes a debug monitor.
To add permanent to the blog don't forget to apply by clicking "Apply to Blog."  This feature makes the blog as you want just changing the CSS style sheet. To change the HTML page is not a good choice unless you have to because you need to remember where those changes in a long HTML code page and sometimes it is confusing and complicated. With CSS you need to remember ID and class that need to change. In both cases you will need to know where the id or class have to be changed whether in HTML or CSS. In case of the template is changed in the future you just paste the CSS lines into Add Custom CSS then you're done. It is much quicker to add these CSS lines than go to HTML page and do the search then changing the sections of HTML.This is the cleanest way.
The only things that you can change HTML/JavaScript and now with CSS on the blogger. HTML/Javascript goes to Layout Add a Gadget then choose HTML/JavaScript to your blog. Then paste HTML or Javascript into this new gadget.

#footer-3, #navbar-iframe
{
  display: none;
}

body {
    -o-background-size: cover;
    background-size: cover;
}
.body-fauxcolumn-outer .cap-top {
    display:none;
}

Note:
# is ID, body is for element called in HTML .body for class body, target more then 1 element need to have comma between in the case  #footer-3, #navbar-iframe here we target 2 IDs: #footer and #navbar to display none. Only 3 lines of code to remove top va bottom of blogger. That is the magic of CSS.


Friday, June 08, 2012

Processes Vs. Threads revisited

http://objectlayer.blogspot.ca/2006/05/thread-vs-process.html
- All threads in a program must run the same executable.A child process, on the
other hand, may run a different executable by calling an exec function.
- An errant thread can harm other threads in the same process because threads
share the same virtual memory space and other resources. For instance, a wild
memory write through an uninitialized pointer in one thread can corrupt
memory visible to another thread.
An errant process, on the other hand, cannot do so because each process has a
copy of the program’s memory space.
- Copying memory for a new process adds an additional performance overhead
relative to creating a new thread. However, the copy is performed only when
the memory is changed, so the penalty is minimal if the child process only reads
memory.
- Threads should be used for programs that need fine-grained parallelism. For
example, if a problem can be broken into multiple, nearly identical tasks, threads
may be a good choice. Processes should be used for programs that need coarser
parallelism.
- Sharing data among threads is trivial because threads share the same memory.
(However, great care must be taken to avoid race conditions, as described previously.)
Sharing data among processes requires the use of IPC mechanisms, as
described in Chapter 5.This can be more cumbersome but makes multiple
processes less likely to suffer from concurrency bugs.
- Thread has its own Code, Data, Stack and Thread is sharing. Each Process has one or more threads and each thread belongs to one process
- Thread is fast for context switch and cheaper than process.
Conceptually, a thread exists within a process.Threads
Simple process for ls

#include <pthread.h>
int main()
{
  int return_value;
  return_value = system ("ls -l /");
  return return_value;
}



#include <pthread.h>
#include <stdio.h>
/* Prints x’s to stderr.*/
void* print_xs (void* unused)
{
    while (1)
    fputc ('x', stderr);
    return NULL;
}
/* The main program.
*/
int main ()
{
    pthread_t thread_id;
    /* Create a new thread. The new thread will run the print_xs
    function. */
    pthread_create (&thread_id, NULL, &print_xs, NULL);
    /* Print o’s continuously to stderr. */
    while (1)
    fputc ('o', stderr);
    return 0;
}
Compile and link this program using the following code:
$ gcc -o thread-create thread-create.c -lpthread
$ ./thread-create
ooooxxxxxxxxxxxxxxooooo

Is linux kernel preemptive or not?

Yes, the kernel is preemptive.
It has been preemptive by default since the 2.6 branch. The old Linux kernel is not preemptive, which means that a process can be preempted only while running in User Mode; non preemptive kernel design is much simpler, since most synchronization problems involving the kernel data structures are easily avoided Prior to Linux kernel version 2.5.4, Linux Kernel was not preemptive which means a process running in kernel mode cannot be moved out of processor until it itself leaves the processor or it starts waiting for some input output operation to get complete.
  Generally a process in user mode can enter into kernel mode using system calls. Previously when the kernel was non-preemptive, a lower priority process could priority invert a higher priority process by denying it access to the processor by repeatedly calling system calls and remaining in the kernel mode. Even if the lower priority process' timeslice expired, it would continue running until it completed its work in the kernel or voluntarily relinquished control. If the higher priority process waiting to run is a text editor in which the user is typing or an MP3 player ready to refill its audio buffer, the result is poor interactive performance. This way non-preemptive kernel was a major drawback at that time.
A preemptive kernel is one that can be interrupted in the middle of a executing code - for instance in response for a system call - to do other things and run other threads, possible that are not in the kernel.
The main advantage in a preemptive kernel is that sys-calls do not block the entire system. if a sys-call takes a long time to finish then it doesn't mean the kernel can't do anything else in this time.
The main disadvantage is that this introduces more complexity to the kernel code, having to handle more end-cases, perform more fine grained locking or use lock-less structures and algorithms.
preemption (more correctly pre-emption) is the act of temporarily interrupting a task being carried out by a computer system, without requiring its cooperation, and with the intention of resuming the task at a later time. Such a change is known as a context switch. It is normally carried out by a privileged task or part of the system known as a preemptive scheduler, which has the power to preempt, or interrupt, and later resume, other tasks in the system.
$ strace echo test                                
execve("/bin/echo", ["echo", "test"], [/* 45 vars */]) = 0       (execve, mmap are system calls)         
brk(0)                                  = 0xc90000  
mmap(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7f4210db7000
access("/etc/ld.so.nohwcap", F_OK)      = -1 ENOENT (No such file or directory)         
mmap(NULL, 8192, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7f4210db5000
mmap(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7f4210c5d000
write(1, "test\n", 5test
)                   = 5
close(1)                                = 0
munmap(0x7f4210c5d000, 4096)            = 0
close(2)                                = 0
exit_group(0)                           = ?

Kernel space and user space


System calls are used when a user space program wants to use some data or some service provided by the Linux kernel. In current Linux kernel (2.6.23) there exist 324 system calls. All system calls provide a function which is useful for many application programs (such as file operations, network operations or process related operations). There is no point in adding a very specific system call which can be used only by a specific program. http://www.kernel.org/doc/man-pages/online/pages/man2/mknod.2.html
A conventional computer operating system usually segregates virtual memory into kernel space and user space. Kernel space is strictly reserved for running the kernel, kernel extensions, and most device drivers. In contrast, user space is the memory area where all user mode applications work and this memory can be swapped out when necessary.
Similarly, the term userland refers to all application software that runs in user space.[1] Userland usually refers to the various programs and libraries that the operating system uses to interact with the kernel: software that performs input/output, manipulates file system objects, etc.
Each user space process normally runs in its own virtual memory space, and, unless explicitly requested, cannot access the memory of other processes. This is the basis for memory protection in today's mainstream operating systems, and a building block for privilege separation. Depending on the privileges, processes can request the kernel to map part of another process's memory space to its own, as is the case for debuggers. Programs can also request shared memory regions with other processes.
Kernel space and user space is the separation of the privileged operating system functions and the restricted user applications. The separation is necessary to prevent user applications from ransacking your computer. It would be a bad thing if any old user program could start writing random data to your hard drive or read memory from another user program's memory space.
User space programs cannot access system resources directly so access is handled on the program's behalf by the operating system kernel. The user space programs typically make such requests of the operating system through system calls.


Write a device driver in Linux

/* Necessary includes for device drivers http://www.freesoftwaremagazine.com/articles/drivers_linux?page=0%2C1 */

#include <linux init.h>

//#include <linux config.h> no more since 2.6.19 deprecated

#include <linux module.h>

#include <linux kernel.h> /* printk() */

#include <linux slab.h> /* kmalloc() */

#include <linux fs.h> /* everything... */

#include <linux errno.h> /* error codes */

#include <linux types.h> /* size_t */

#include <linux proc_fs.h>

#include <linux fcntl.h> /* O_ACCMODE */

#include <asm system.h> /* cli(), *_flags */

#include <asm uaccess.h> /* copy_from/to_user */



MODULE_LICENSE("Dual BSD/GPL");



/* Declaration of memory.c functions */

int memory_open(struct inode *inode, struct file *filp);

int memory_release(struct inode *inode, struct file *filp);

ssize_t memory_read(struct file *filp, char *buf, size_t count, loff_t *f_pos);

ssize_t memory_write(struct file *filp, char *buf, size_t count, loff_t *f_pos);

void memory_exit(void);

int memory_init(void);



/* Structure that declares the usual file */

/* access functions */

struct file_operations memory_fops = {

  read: memory_read,

  write: memory_write,

  open: memory_open,

  release: memory_release

};



/* Declaration of the init and exit functions */

module_init(memory_init);

module_exit(memory_exit);



/* Global variables of the driver */

/* Major number */

int memory_major = 60;

/* Buffer to store data */

char *memory_buffer;



int memory_init(void) {

  int result;



  /* Registering device */

  result = register_chrdev(memory_major, "memory", &memory_fops);

  if (result < 0) {

    printk(

      "<1>memory: cannot obtain major number %d\n", memory_major);

    return result;

  }



  /* Allocating memory for the buffer */

  memory_buffer = kmalloc(1, GFP_KERNEL); 

  if (!memory_buffer) { 

    result = -ENOMEM;

    goto fail; 

  } 

  memset(memory_buffer, 0, 1);



  printk("<1>Inserting memory module\n"); 

  return 0;



  fail: 

    memory_exit(); 

    return result;

}



void memory_exit(void) {

  /* Freeing the major number */

  unregister_chrdev(memory_major, "memory");



  /* Freeing buffer memory */

  if (memory_buffer) {

    kfree(memory_buffer);

  }



  printk("<1>Removing memory module\n");



}



int memory_open(struct inode *inode, struct file *filp) {



  /* Success */

  return 0;

}

int memory_release(struct inode *inode, struct file *filp) {



  /* Success */

  return 0;

}

ssize_t memory_read(struct file *filp, char *buf, 

                    size_t count, loff_t *f_pos) { 



  /* Transfering data to user space */ 

  copy_to_user(buf,memory_buffer,1);



  /* Changing reading position as best suits */ 

  if (*f_pos == 0) { 

    *f_pos+=1; 

    return 1; 

  } else { 

    return 0; 

  }

}

ssize_t memory_write( struct file *filp, char *buf,

                      size_t count, loff_t *f_pos) {



  char *tmp;



  tmp=buf+count-1;

  copy_from_user(memory_buffer,tmp,1);

  return 1;

}

///----Makefile
obj-m = hello.o memory.o
KVERSION = $(shell uname -r)
all:
    make -C /lib/modules/$(KVERSION)/build M=$(PWD) modules
clean:
    make -C /lib/modules/$(KVERSION)/build M=$(PWD) clean
///----Testing after make
$sudo nsmod memory.ko
$sudo rmmod memory.ko
$ dmesg | less
[223447.209899] Inserting memory module
[223629.779878] Removing memory module
[223663.099549] Loading hello module...
# mknod /dev/memory c 60 0 (make device using system call see http://www.kernel.org/doc/man-pages/online/pages/man2/mknod.2.html  In the above, c means that a char device is to be created, 60 is the major number and 0 is the minor number.)
Insert character into the device
#chmod 666 /dev/memory
#insmod memory.ko
#echo -n ABC > /dev/memory
#cat /dev/memory
C
Note: .ko kernel object,.so /usr/lib (library), .ro (module plugin gedit)
.o for object then link gcc -o test test.c

Questions:
Q. Can you explain me what is device files and how do I access or see device files? Why UNIX / Linux has device files?
A. Under Linux and UNIX each and every hardware device treated as a file. A device file allows to accesses hardware devices so that end users do not need to get technical details about hardware.
In short, a device file (also called as a special file) is an interface for a device driver that appears in a file system as if it were an ordinary file. This allows software to interact with the device driver using standard input/output system calls, which simplifies many tasks.

Device file two types

There are two types of device files based upon how data written to them and read from them is processed by the operating system and hardware:
  • Character special files or Character devices
  • Block special files or Block devices

Understanding Character special files or Character devices

  • Talks to devices in a character by character (1 byte at a time)
  • Examples: Virtual terminals, terminals and serial modems etc

Understanding Block special files or Block devices

  • Talks to devices 1 block at a time ( 1 block = 512 bytes to 32KB)
  • Examples: Hard disk, DVD/CD ROM, and memory regions etc

Why use device files?

Device file allows transparent communication between user space applications and computer hardware.

What is a Zombie process?

http://en.wikipedia.org/wiki/Zombie_process On Unix and Unix-like computer operating systems, a zombie process or defunct process is a process that has completed execution but still has an entry in the process table. This entry is still needed to allow the parent process to read its child's exit status. The term zombie process derives from the common definition of zombie — an undead person. In the term's metaphor, the child process has "died" but has not yet been "reaped". Also, unlike normal processes, the kill command has no effect on a zombie process.

How do I kill zombie process?

You cannot kill zombies, as they are already dead. But if you have too many zombies then kill parent process or restart service.
You can kill zombie process using PID obtained from any one of the above command. For example kill zombie process having PID 4104:
# kill -9 4104
create zombie.c

#include <stdlib.h&g

#include <sys types.h&g

#include <unistd.h&g



int main ()

{

pid_t child_pid;



child_pid = fork (); // system call to create a new process referred to as the child process

if (child_pid > 0) {

sleep (60);

}

else {

exit (0);                  // parent exist make child becomes zombie if the parent crashes makes it becomes

}                             // orphan process will waste resources but zombie is no harm except running out PID

return 0;

}

gcc zombie.c -o zombie
./zombie
after 1 minute
ps -ax
  1815 ?        Sl     0:00 /usr/bin/python /usr/bin/bzr-notify
 6314 pts/1    S+     0:00 ./zombie
 6315 pts/1    Z+     0:00 [zombie]
The child process is marked as , and its status code is Z, for zombie.
When the program exits, the child process is inherited by init. This process should cleans up the zombie proces automatically.

Zombie vs. Orphan process

http://en.wikipedia.org/wiki/Zombie_process
On Unix and Unix-like computer operating systems, a zombie process or defunct process is a process that has completed execution but still has an entry in the process table. This entry is still needed to allow the parent process to read its child's exit status. The term zombie process derives from the common definition of zombie — an undead person. In the term's metaphor, the child process has "died" but has not yet been "reaped". Also, unlike normal processes, the kill command has no effect on a zombie process.
A zombie process is not the same as an orphan process. An orphan process is a process that is still executing, but whose parent has died. They do not become zombie processes; instead, they are adopted by init (process ID 1), which waits on its children.

Thursday, June 07, 2012

Java Threads for Hello World

//Extends Threads class DispThread extends Thread {
String msg;

    public void run() {
    try {
    for(int i = 2; i > 0; i--) {  //delay
    System.out.println("Child Thread: " + i);
    Thread.sleep(10000);
    }
    } catch (InterruptedException e) {
        System.out.println("Child interrupted.");
    }
      
        System.out.println("Exiting child thread." + msg);
    }
    public DispThread(String m){
        msg = m;
    }
}
class ThreadTest {
    public static void main(String args[]) {
   
      DispThread dt1 = new DispThread("Hello");
      DispThread dt2 = new DispThread("World");
      dt1.start();  // call user thread from main thread
      dt2.start();
   
    }
}
With the delay the output
Running tool: javac

javac ThreadTest.java
java ThreadTest
Child Thread: 2
Child Thread: 2
Child Thread: 1
Child Thread: 1
Exiting child thread.Hello
Exiting child thread.World

Done.

//Implements Runnable
class DispThread implements Runnable {
String msg;

    public void run() {
    try {
   for(int i = 5; i > 0; i--) {  //delay or sleep
    System.out.println("Child Thread: " + i);
    Thread.sleep(500);
     }
    } catch (InterruptedException e) {
       System.out.println("Child interrupted.");
      }
        System.out.println("Exiting child thread." + msg);
    }
    public DispThread(String m){
        msg = m;
    }
}

class ThreadTest1 {
    public static void main(String args[]) {
   
      DispThread dt1 = new DispThread("Hello");
      DispThread dt2 = new DispThread("World");
      Thread t1 = new Thread(dt1);   //because implements need to create an object
      Thread t2 = new Thread(dt2);
      t1.start();
      t2.start();
   
    }
}
//Without delay the output
Running tool: javac

javac ThreadTest1.java
java ThreadTest1
Exiting child thread.World
Exiting child thread.Hello

Done.

//No Thread just println
public class Hi {
public static void main(String argv[]){
   System.out.println("Hello World");
   }
}
javac Hi
Hello World

Done.

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;
}

Interface (virtual function in C++) - Polymorphism

interface Animal
{

    String getName();   //Abstract String getName() is ok too??
    String talk();
}


class Cat implements Animal
{
    public String name;
    public Cat(String name)   //constructor
    {       
        this.name = name;
        //System.out.println(name);
    }

    public String talk()
    {
        return "Meowww!";
    }

    @Override
    public String getName() {
        // TODO Auto-generated method stub
        System.out.println("GetnameCat = " + name);
        return name;
    }
}

class Dog implements Animal
{
    public String name;
    public Dog(String name)
    {
        this.name = name;
    }

    public String talk()
    {
        return "Arf! Arf! Arf!";
    }

    @Override
    public String getName() {
        // TODO Auto-generated method stub
        System.out.println("GetnameDog = " + name);
        return name;
    }
}

class TestAnimals     //name has to be in this case with or without public is ok 
{
    // prints the following:
    //
    // Missy: Meowww!
    // Mr. Mistoffelees: Meowww!
    // Lassie: Arf! Arf!
    //
    public static void main(String[] args)
    {

              
           Animal[] animals =
        {
            new Cat("Missy"),
            new Cat("Mr. Mistoffelees"),
            new Dog("Lassie")
        };
     
//java for each Loops without index otherwise (int i; i < animals.length; i++)
              for (Animal a: animals)
            {
            System.out.println(a.getName() + ": " + a.talk());
            }
    }
//--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[] =
        {
                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;
}
UML: Generated by Umbrello: Import the code to generate the diagram or diagram to code generating it can be used to understand OOP or see how it translates between Java and C++ with very limited. It is great to study it is easy to use but not that good as Rational Rose. It is running under linux.