RTTI

*Run Time Type Identification
*enables us to identify type an object during execution of program

*RTTI operators are runtime events for polymorphic classes and compile time events for all other types.
* two type of RTTI operators  are:
     1. typeid
      2. dynamic_cast

typeid
*typeid is an operator which returns refrence to object of type_info class
*Type_info class describers type of object

#include<type_info.h>
main()
{
int i,j;
float f;
char* p;
A a;
B b;

cout<<"type of i is "<<typeid(i).name();//int
cout<<"type of f is "<<typeid(i).name(); //float
cout<<"type of p is "<<typeid(i).name(); //char*
cout<<"type of a is "<<typeid(i).name();//class A
cout<<"type of b is "<<typeid(i).name(); //class B
}


casting operators
*dynamic_cast
*static_cast
*cont_cast
*reinterpret_cast

syntax:
cast_name<type>(expression)

 



Binding

*Binding is an association of function calls to an objects.
*The normal bidind of member function call with an object is referred as compile time or static type or early binding
*c++ also supports runtime binding or dynamic binding or late binding


function binding:
binding  refers to the connection between a function call and the actual code executed as the result of the call.

in the process of an .exe file ,wherever the Linker encounters the  function call statement,it links it with that function difinition.which function definition to link the function call with ,is resolved by the compiler by mapping the logical addresses of the definitions at the compile-time itself.this process is called compile-time or static or early binding.

whenever the generic pointer is holding the address of the object of a derived class,and any function is invoked using that pointer,the compiler is unable to resolve this call at compile time .this is because the compiler can not invoke the appropriate function since the generic pointer will actually hold the address or will be type cast at run-time ()thats why it uses the static type of the pointer to govern the method invocation )

but in order to invoke the approprate function (i.e of the derived class),the compiler needs  to bind that funcion call to the correct function definition.The decision of which function to be invoked is taken at a later stage(i.e at run time).hence this feature is referred to as late (i.e run time)binding.This pointer is capable of pointing to an object at run time.hence it can invoke any function dynamically depending upon the type of the object that it is pointing to or the type of the object that it is type cast to.thats why it is also referred to as dynamic binding.
C++ supports this feature of dynamic biniding ny allowing us to typecast the generic pointer to the type of the object that it is pointing to.

Dangling pointer

Arising due to having lost the memory to which a pointer is suppose to be pointing at.in this case if we try to use the pointer the program may give unpredictictable results.

Scope of an object

class Test
{
 public:
      Test()
         {
        cout<<"constructor invoked"<<endl;
          }
     ~Test()
         {
        cout<<"Destructor invoked"<<endl;
          }
};



Test t1;
 void main(void)
{
cout<<"main begins";
Test t2;
{
cout<<"Block begins" <<endl;
Test t3;
cout<<"block Ends"<<endl;
}
cout<<"main ends"<<endl;
}



Output:
constructor invoked//for t1
main begins
constructor invoked//for t2
block begins
constructor invoked//for t3
block ends
Destructor invoked//for t3
main ends
Destructor invoked//for t2
Destructor invoked//for t1


Memory Leakage

Memory  Leakage:
Arising due to having lost the pointer to some memory that is allocated on heap.in this case the memory remains allocated and can't be freed because it's base address is lost.it leads to substantial wastage of the free storage on the heap.


int *p=new int[1000];
----
----
delete []p;

4bytes
------------
4000bytes

if delete p
only first 4 bytes freed which results in memory leakage of 3996 bytes

Note:Also it is very important to note that whenever we have allocated memory for more than one element i.e using subscript notation [size],it becomes necessary to de-allocate the memory by using the subscript notation [] in the delete operator as shown above.if this is not done and a delete  statement without a pair of
 [ ] is used,then only the first element whose address is contained in the pointer is deallocated resulting in the problem of memory leakage.

Memory leak
Memory leaks can be really annoying. The following list describes some scenarios that result in memory leaks.
  • Reassignment I'll use an example to explain reassignment.
    char *memoryArea = malloc(10);
    char *newArea = malloc(10);

    This assigns values to the memory locations shown in Figure 4 below.


    Figure 4. Memory locations


    memoryArea and newArea have been allocated 10 bytes each and their respective contents are shown in Figure 4. If somebody executes the statement shown below (pointer reassignment )…
    memoryArea = newArea; 

    then it will surely take you into tough times in the later stages of this module development.In the code statement above, the developer has assigned the memoryArea pointer to the newArea pointer. As a result, the memory location to which memoryArea was pointing to earlier becomes an orphan, as shown in Figure 5 below. It cannot be freed, as there is no reference to this location. This will result in a memory leak of 10 bytes.


    Figure 5. Memory leak


    Before assigning the pointers, make sure memory locations are not becoming orphaned.
  • Freeing the parent block first Suppose there is a pointer memoryArea pointing to a memory location of 10 bytes. The third byte of this memory location further points to some other dynamically allocated memory location of 10 bytes, as shown in Figure 6.


    Figure 6. Dynamically allocated memory


    free(memoryArea)

    If memoryArea is freed by making a call to free, then as a result the newArea pointer also will become invalid. The memory location to which newArea was pointing cannot be freed, as there is no pointer left pointing to that location. In other words, the memory location pointed by newArea becomes an orphan and results in memory leak.
    Whenever freeing the structured element, which in turn contains the pointer to dynamically allocated memory location, first traverse to the child memory location (newArea in the example) and start freeing from there, traversing back to the parent node.
    The correct implementation here will be:
    free( memoryArea->newArea);
    free(memoryArea);
  • Improper handling of return values At time, some functions return the reference to dynamically allocated memory. It becomes the responsibility of the calling function to keep track of this memory location and handle it properly.
    char *func ( )
    {
      return malloc(20); // make sure to memset this location to ‘\0’…
    }
    
    void callingFunc ( )
    {
      func ( ); // Problem lies here
    }

    In the example above, the call to the func() function inside the callingFunc() function is not handling the return address of the memory location. As a result, the 20 byte block allocated by the func() function is lost and results in a memory leak.


C++: Reference Variable:



C++:
Reference Variable:
Reference is an alias created for the variable.
Anallogy:Nickname

Important  example:
int  a=10;
  int &b=a;
  cout<<"value a="<<a;
  cout<<"value b="<<b; 
O/P:
Value a=10
Value b=10

& is a reference operator.syntax  int  &b=a; creatres another name b for the variable a.  i.e we can say b is a reference to a.
If we manipulate the value of b e.g b=10  then the value of a gets changed.
int a=10;
  int &b=a;
  b=20;
  cout<<"valu a"<<a;
  cout<<"valu b"<<b; 
o/p:
Value a=20
Value b=20

WHILE USING REFERENCE WE SHOULD KNOW……..
Reference have to be initialized
No memory is allocated to reference
Difference between pointer and reference
Pointer is flexible collaction
Reference is a rgid collection
Int *p=&I;
Int k;
P=&k;

A pointer has to be de-referenced before you can access the value at the addres contained in it. A reference is moreover a direct connection as it’s just another name for the same memory location.
We can have an arry of pointers whereas we can not have an aray of reference.

Const keyword
Constants should be initialized
Int i=10;
Const int*p=&I;
P=&k(correct)                                                                     (*p)++       incorrect
P++(correct)                                                                         *p=20 incorrect

Here,the pointer itself is not a constant and neither is the integer that it is pointing tp, a constant.we can change the address in the pointer by assigning some other address to it.but we cannot modify the contgents of the variable that it is pointing to,through that pointer.

Note:See some other cases like
1.pointer to a constant integer
2.contant pointer to an integer
3.constant pointer to a constant integer








                                               

   
     


class A
{
}
class B{
void me()
{
System.out.println(“hello you are inside B’s me method”);
}
}

Class C
{
public static void main(String a[])
{
A a=new B();
d.me();
}
}



A  d                       =                                 new B();

Referencing                                  create a memory for a object of type B




Here d is a veriable of class A and pointing to a memory  of type class B.
d.me()
here d check the body of me() method inside the A class wheather it be blank doesn’t metter but it should be .
if it doesn’t  find  then it gives error at compile time.
When program becomes successful compiled then at runtime it goes to the memory of type B and search there about method me()


constructor



class One
{
  One()
{
   System.out.println("One");
}
}
class Two extends One
{
   Two()
{
   System.out.println("Two");
}
}
class Super2
{
   public static void main(String args[])
{
   Two t=new Two();
}
}




The first  line of every constructor is 
super();
that is every constructor call its super class constructor  first;






Abstract



Abstract method: abstract method is a method which doesn’t  contains body in that class where it declares. Definitely It has a body in that class in which it becomes inherited .It may or may not has keyword  “abstract” when is declared in a interface but has keyword “abstract” when it becomes declared inside a abstract class .every  concrete class has a body( at least  empty body) of every abstract method to which concrete class keeping inherit
Abstract class:  every class which starts with “abstract” keyword and contained atleast one abstract method is known a abstract class it may has concrete method.  we   can’t  make instance of abstract class.
We can call constructor of abstract class using child class’s constructor since every constructor of class has  super() in its first line which calls the super class constructor.
Interface: interface is just like class but it it is created using interface keyword. Interface has all its method abstract by default and final field by default. Fields should be declared and initialized in same line.



  

Java Language package

 
sepbar-1.gif (3106 bytes)

 Java Language package


Java provides a rich set of pre-written classes, giving programmers an existing library of code to support files, networking, graphics, and general language routines; each major category being supported by a collection of classes known as a package. I'll be covering each of these packages in a later part of the tutorial series, but for now, will introduce you to one of the most important packages of all - java.lang.
By default, each Java application/applet has access to the java.lang package. Inside java.lang are classes that represent primitive data types (such as int & char), as well as more complex classes. It contains classes pertaining to strings, string buffers, threads, and even the System class from which we obtain out input and output streams. Java.lang is quite extensive, and some aspects (such as threads) can be confusing for those new to the Java language. For this reason, I'll only present the more useful, less complex, parts of this package. This should allow you to experiment with some of the handy features of the Java language, while minimising the barrier to understanding. For more advanced Java programmers, you may wish to consult the Java API yourself, and experiment with other parts of java.lang not covered herein.

Basic data types

We've used some of the simple data types, such as strings and floating point numbers (double), but haven't actually looked at some of their methods. Below, I'll cover some of the more important data types :
  • Object
  • Integer
  • Long
  • Float
  • Double
  • Character
  • String
  • StringBuffer

Class Object

In Java, all classes are actually subclasses of class Object. In a previous tutorial, we covered what it meant to extend a class, and the syntax for creating new classes.
When we define a class,

class MyClass
{
  .....
}

we are actually implicitly extending MyClass from class Object. Thus, we can replace the above sample with the following :

class MyClass extends Object
{
  .....
}
At first glance, this might not appear to be very important, except for academic interest. However, it actually has a profound impact - every class in Java shares the same properties, and hence methods of class Object. While there are several methods that might be of use, the most important of these is the toString() method.
Every object can be explicitly converted into a string representation, by calling the toString() method which returns a string. Thus, we can explicitly convert objects, such as floating point numbers, integers, etc. If you construct a class yourself, you should consider overriding the toString method, to provide a suitable return value.

        double my_double = 3.14;
        String my_str = my_double.toString()



Numerical data types

The numerical data types all share some common methods, which their inherit from class Number. All numbers are convertible to the basic numerical classes (int, long, float, double) using the following method calls :

        int    intValue();
        long   longValue();
        float  floatValue();
        double doubleValue();




Class Integer / Long

Integer, and the longer form, long, represent whole number values. Integers and longs can be interchanged through the longValue() and intValue() methods, and can also be converted to floats and doubles using the floatValue() and doubleValue().

        Integer my_integer = new Integer(256);
        Long my_long = my_integer.longValue();




Class Float / Double

Floating point values, and the longer form, double, represent decimal (fractional) values. Floats and doubles can be interchanged through the doubleValue() and floatValue() methods, and can also be converted to integers and longs using the longValue() and intValue() methods. Its important to remember, however, that there will be a loss of precision, as integers and longs cannot retain the fractional component.

        Float my_float = new Float(3.14);
        Double my_double = new Double (my_float.doubleValue());

        // Print out double (3.14)
        System.out.println( "Double : " + my_double);

        // Print out integer (3)
        System.out.println( "Integer: " + my_double.intValue() );




Class Character

The character class contains a large set of character comparison routines, in the form of static methods. We haven't really discussed static methods before - a static method is a method that is common to all objects of the type that class. In fact, you don't even need to instantiate an object from a class containing a static method to call it!

        if (Character.isLowerCase( 'H' ))
        {
                System.out.println ("Lowercase value detected");
        }
        else
        {
                System.out.println ("Uppercase value detected");
        }
The character class offers a wide range of character comparison routines; the most useful are listed below :

        static boolean isDigit( char c );
        static boolean isLetter( char c );
        static boolean isLetterOrDigit( char c );
        static boolean isLowerCase( char c );
        static boolean isUpperCase( char c );

        static char    toUpperCase( char c );
        static char    toLowerCase( char c );




Class String

Programmers who are familiar with C will understand a string as being an array of characters. Though Java has aspects of C/C++, the definition for a string differs strongly. Under Java, a string is a unique object, which has its own set of methods. Gone are the days of importing a string library, we simply invoke methods of a string object. Some of the more useful routines are listed below :

     // Returns the character at offset index
     public char charAt(int  index);

     // Compares string with another, returning 0 if there's a match
     public int compareTo(String  anotherString);

     // Returns a new string equal to anotherString
     // appended to the current string
     public String concat(String  anotherString);

    // Returns the length of the current string
    public int length();

    // Returns true if the current string begins with prefix
    public boolean startsWith(String  prefix);

    // Returns true if the current string ends in suffix
    public boolean endsWith(String  suffix);

    // Returns the remainder of the string, starting from offset beginIndex
    public String substring(int  beginIndex);

    // Returns a substring from offset beginIndex to offset endIndex
    public String substring(int  beginIndex, int endIndex);

    // Returns the current string, converted to lowercase
    public String toLowerCase();

    // Returns the current string, converted to uppercase
    public String toUpperCase();





Class StringBuffer

While strings are extremely useful, there are some tasks that require a more flexible sequence of characters. In cases where strings are being constantly modified, and appended to, it is not always efficient to simply recreate a string every time you wish to concatenate it with another. The StringBuffer class has an append method, which extends the capacity of the StringBuffer when required to accommodate varying lengths. The append method even allows you to add chars, booleans, integers, longs, floats & doubles.
Some of the more useful StringBuffer methods are given below :

    // Appends the string version of a boolean to the buffer
    public StringBuffer append(boolean  b);

    // Appends a character to the buffer
    public StringBuffer append(char  c);

    // Appends the string version of a integer to the buffer
    public StringBuffer append(int  i);

    // Appends the string version of a long to the buffer
    public StringBuffer append(long  l);

    // Appends the string version of a float to the buffer
    public StringBuffer append(float  f);

    // Appends the string version of a double to the buffer
    public StringBuffer append(double  d);

    // Appends the string version (toString method) of an object to the buffer
    public StringBuffer append(Object  obj);

    // Appends the string to the buffer
    public StringBuffer append(String  str);

    // Returns the character at offset index
    public char charAt(int  index);

    // Returns the current length of the string buffer
    public int length();

    // Reverses the order of characters in the string buffer
    public StringBuffer reverse();

    // Truncates, or pads with null characters, the buffer to a certain length
    public void setLength(int  newLength);

    // Returns a string, representing the string buffer
    public String toString();




Class System

The System class is perhaps one of the most important classes contained within the java.lang package, as this class provides us with the input and output streams. Without these, it would be very difficult to interact with the user!

    public static InputStream in;
    public static PrintStream out;
    public static PrintStream err;
There is one input stream, and two output streams (out/err). Normal messages should be passed to out, but exceptional cases and error conditions should be written to err (standard error on Unix systems). Since these attributes are static, we need not even instantiate the System class to access them. To print, for example, we can simply use the statement System.out.println()
The System class also has some interesting methods which are of use to Java programmers.

    public static void exit(int  status)
    public static String getProperty(String  key);

System.exit

Exit allows a Java programmer to immediately terminate execution of the program, and to return a status code. By convention, a non-zero status code indicates an error has occurred, and on PC systems, should set the appropriate DOS errorlevel.
If your Java application has been run from a batch file, you can actually test to see if it has executed correctly. Presented below is a test class, and a batch file that when executed will check for a status code of six.


class test
{
        public static void main(String args[])
        {
                System.exit (6);
        }

}

Listing 1.0 - Test.java

@echo off
if ERRORLEVEL 6 echo Errorlevel 1 detected
REM Execute test.class
java test
if ERRORLEVEL 6 echo An error has occurred. Please restart

Listing 1.1 - Test.bat

A check is made, in two places, to see if errorlevel six has been set, so that the change in errorlevel can be seen. Its also important to note that an errorlevel will last longer than the duration of the batch file - running test.bat a second time will mean that the first error check returns true.




System.getProperty

Another useful method from the System class is getProperty. Via the getProperty method, a Java application can gain information about the operating system under which it is running, the vendor and version of the Java virtual machine, and even the user name and home directory path of the current user under Unix based systems.
Some of the more common system properties are listed in the table below.
Key Description of associated value
java.version Java version number
java.vendor Java-vendor-specific string
java.vendor.url Java vendor URL
java.home Java installation directory
java.class.version Java class format version number
java.class.path Java classpath
os.name Operating system name
os.arch Operating system architecture
os.version Operating system version
file.separator File separator ("/" on Unix)
path.separator Path separator (":" on Unix)
line.separator Line separator ("\n" on Unix)
user.name User account name
user.home User home directory
user.dir User's current working directory

Table 1.0 - getProperty key/value pairs
Accessing the system properties is as simple as calling the static getProperty method and passing a key from the table as a parameter. An example is shown below, which displays the operating system of the computer it is running on.

class GetPropertyDemo
{
        public static void main(String args[])
        {
                // Display value for key os.name
                System.out.println ( System.getProperty("os.name") );
        }
}



At the conclusion of this tutorial, you should be more familiar with the java.lang package, and the classes contained within. For extra practice, you should consider writing a few programs of yourself, using number conversion and string manipulation. Practice with the classes in java.lang should prepare you for the next challenge - that of Java's graphical/utility/network packages.


Counters