Tuesday, May 15, 2012

Introduction to JavaScript

This is the content for a presentation on JavaScript. I just made the content publicly available for interested people who attended the session. Most of the slides are very informative though so that anyone could make use of hopefully.

I'll be visiting the content and adding more clarification soon.

The Name: JavaScript

  • Prefix: Java

    Is it related to Java? A subset maybe?


    It has nothing to do with Java

  • Suffix: Script

    Is it just a scripting language?

    Not a real programming language?


    It is a complete programming language


  • Available in all browsers

  • The most popular programming language

The Most Misunderstood Programming Language

  • The name

    prefix and suffix

  • It is different

    Programmers don't even bother to learn it

  • Unfairly blamed for the awfulness of the DOM

  • Previous bad implementations

  • Lack of good books

Design: Very Good Ideas

  • Functions are first class objects

    They can be passed as arguments and return values

  • Loose Typing

    Easier - more expressive

  • Dynamic Objects

    General containers = hash tables

  • Object Literal Notation

    Very expressive

Design: Controversial Ideas

  • Prototypal Inheritance

    • No Classes

    • Objects inherit directly form other objects

    • Very powerful

    • Not commonly understood very well

Design: Very Bad Ideas

  • Linkage through global variables

    • Compilation units (scipt tags) are combined in a commmon global namespace

    • Variables can collide

Types (Values)

  • Simple types

    • Numbers

    • Strings

    • Booleans

    • null

    • undefined

  • Objects


  • Only one number type

  • 64-bit floating point (same as Java's double)

    0.1 + 0.2      // 0.30000000000000004
  • 100, 100.0, 1e2 are equivalent

  • NaN and Infinity are special numbers

Numbers: NaN

  • Special Number: Not a Number

  • Result of erroneous operations

    2 * 'a'       // NaN
  • Toxic

    5 + NaN       // NaN
  • Not equal to any value (including itself)

    NaN == NaN       // false
    isNaN(NaN)       // true

Numbers: Infinity

  • Special Number

    1 / 0           // Infinity
    1 / Infinity    // 0
  • Represents numbers > 1.79769313486231570e+308

    1.8e308       // Infinity

Numbers: Number function

  • Converts a value into a number

    Number('')          // 0
    Number('0032')      // 32
    Number('123abc')    // NaN
    Number('abc')       // NaN
  • So does the '+' prefix operator

    +''                // 0
    +'0032'            // 32
    +'123abc'          // NaN
    +'abc'             // NaN

Numbers: parseInt

  • Also converts a value into a number

  • Stops at first non-digit character

    parseInt('123abc', 10)     // 123
  • If no radix is passed it defaults to 10 (8 if input starts with 0)

    parseInt('32')         // 32   (as decimal)
    parseInt('0032')       // 26   (as octal if starts with 0)
  • Always specify the radix

    parseInt('0032', 10)   // 32
    parseInt('0032', 8)    // 26

Numbers: Math

  • An object containing methods that act on numbers

    abs, acos, asin, atan, atan2, ceil, cos, exp, floor, log, max, min, pow, random, round, sin, sqrt, tan

    Math.floor(12.53)          // 12
  • Also contains some useful constants

    E, LN10, LN2, LOG10E, LOG2E, PI, SQRT1_2, SQRT2

    Math.PI                   // 3.141592653589793


  • 0 or more 16-bit characters

  • A character is just a String of length 1

  • Immutable

  • String literal

    'abc' == "abc"    // true
  • length property (number of 16-bit characters)

    'abc'.length      // 3


  • Concatenating

    'Java' + 'Script'     // 'JavaScript'
  • String function

    String(123)           // '123'
  • Strings have methods

    'cat'.toUpperCase()   // 'CAT'


  • true - false

  • Boolean function

    Boolean(truthy_value)    // true
  • !! prefex operator

    !! falsy_value          // false


  • A value that is not anything


  • A value that is not even a value

  • The default value for variables and parameters

  • The value of missing members of an object

Falsy values

  • 6 possible falsy values

    !! false         // false
    !! null          // false
    !! undefined     // false
    !! ''            // false
    !! 0             // false
    !! NaN           // false
  • All other values are truthy

    !! '0'          // true


  • An object is a container of properties

  • A property has a name (string) and value (any type)

  • Class-free (No constraints on names/values of new properties)

  • Objects are hash tables

  • Protype linkage

  • Arrays, functions, regular expressions and objects are objects

Objects: Object literal

  • Very convenient for creating new object values

  • A pair of curly braces surrounding 0+ name/value pairs

    var empty_object = {};
    var person = { 'first-name': 'John' };
    var city = {
      name: 'Alexandria',
      location: { latitude: 31.2, longitude: 29.9 }

Objects: Retrieval

  • Subscript notation

    person['first-name']    // 'John'
    city['name']            // 'Alexandria'
  • Dot notation

    city.name               // 'Alexandria'
    city.location.latitude  // 31.2
  • Missing properties

    person.nickname        // undefined

Objects: Retrieval

  • || operator (set default values)

    var name = person.nickname || 'anonymous';    // 'anonymous'
  • && operator (handle missing nested objects)

    city.country                       // undefined 
    city.country.name                  // throws a TypeError
    city.country && city.country.name  // undefined

Objects: Update

  • Simply by assignment

    person['first-name'] = 'Thomas';    // Replaced 'first-name'
    person['last-name'] = 'Anderson';   // Added 'last-name'

Objects: Reference

  • Objects are passed around by reference

    var x = person;    // x & person refer to the same object
    x.nickname = 'Neo';
    person.nickname    // 'Neo'
    var a = {}, b = {}, c = {};      // different empty objects
    var a = b = c = {};              // the same empty object

Objects: Prototype

  • Every object is linked to a prototype object

  • Objects created by object literal are linked to Object.prototype

    Object.prototype.foo = 'bar';
    var a = {}, b = {};
    a.foo      // 'bar'
    b.foo      // 'bar'
  • Protype link is used only for retrieval (prototype chain)

    a.foo = 'blah';  // Added foo property to a
    a.foo            // 'blah'
    b.foo            // 'bar'

Objects: Prototype

  • We can specify the prototype for a new object

  • Complex but simplified by Object.create function (in new JS editions)

    if (typeof Object.create != 'function') {
      Object.create = function(o) {
        var F = function F(){};
        F.prototype = o;
        return new F();
    var p = {foo: 'bar'};
    var a = Object.create(p);
    a.foo          // 'bar'

Objects: Reflection

  • hasOwnProperty

    Object.prototype.foo = 'bar';
    var a = {foo: 'blah'}, b = {};
    a.foo      // 'blah'
    b.foo      // 'bar'
    a.hasOwnProperty('foo')    // true
    b.hasOwnProperty('foo')    // false

Objects: Enumeration

  • for in

    var someone = {'first-name': 'John', 'last-name': 'Doe'};
    var person = Object.create(someone);
    person.profession = 'artist';
    person.age = 30;
    for (p in person) {
      var mark = person.hasOwnProperty(p) ? '  ' : '* '
      console.log(mark + p + ': ' + person[p]);
    //   profession: artist
    //   age: 30
    // * first-name: John
    // * last-name: Doe

Objects: Delete

  • delete removes a property from an object

    delete person.age;
    person.age                       // undefined
  • May let a prototype property shine through

    person['first-name'] = 'Jason';
    person['first-name']             // 'Jason'
    delete person['first-name']
    person['first-name']             // 'John'

Objects: Reducing Global Footprint

  • A single global variable for your application

    var MyAPP = {};
  • Contains all your variables (as properties)

    MyAPP.someone = {'first-name': 'John', 'last-name': 'Doe'};
    MyApp.person = Object.create(MyAPP.someone);


  • The best thing in JavaScript

  • A function encloses a set of statements that execute when invoked

  • Functions are objects

    • Linked to a prototype (Function.prototype)

    • Can be stored in variables, objects, and arrays

    • Can be passed as arguments to functions and can be returned from functions

  • A function has a prototype property

  • Uses:

    • Code reuse, Information hiding, Composition

Functions: Function Literal

  • 4 parts:

    1. function (reserved word)

    2. name (optional)

    3. parameters

    4. body

    var add = function (a, b) {
      return a + b;

Functions: Invocation

  • Extra parameters: this & arguments

  • Invocation Patterns

    1. Method invocation pattern

    2. Function invocation pattern

    3. Constructor invocation pattern

    4. Apply invocation pattern

  • Arguments

    • No error if not matching number of parameters

    • Extra arguments are ignored

    • Missing will be undefined

Functions: Method Invocation Pattern

  • Function is stored as a property of an object

  • this will be the object

    var myObject = {
      value: 0,
      increment: function (inc) {
        this.value += inc;
    myObject.value;                      // 3

Functions: Function Invocation Pattern

  • Function is not a property of an object

  • this will be the global object (design mistake)

    myObject.double = function () {
      var that = this;      // Workaround.
      var helper = function () {
        that.value = 2 * that.value
      helper();             // Invoke helper as a function.
    myObject.double();      // Invoke double as a method.
    myObject.getValue();    // 4

Functions: Constructor Invocation Pattern

  • Invoked with new prefix

  • A new object is created & linked to function's prototype property

  • this is bound to the new object

    var Car = function (speed) {
      this.speed = speed;
    Car.prototype.move = function() {
      return 'moving at ' + this.speed;
    var my_car = new Car('40 k/h');
    my_car.move();                 // moving at 40 k/h

Functions: Apply Invocation Pattern

  • apply is a method of functions

  • 2 parameters: value for this & array of arguments

    var util = {
      get_status: function(uppercase){
        return uppercase ?
          this.status.toUpperCase() : this.status;
    var obj = { status: 'ok' };
    util.get_status.apply(obj, [true]);      // 'OK'

Functions: Arguments

  • arguments: array of parameters passed to a function

  • array-like object

    var sum = function () {
      var i, s = 0;
      for (i = 0; i < arguments.length; i += 1) {
          s += arguments[i];
      return s;
    sum(4, 8, 15, 16, 23, 42)         // 108

Functions: Return

  • Functions always return a value

  • If no return value is given undefined is returned

  • If invoked with new and no return is given the new object is returned

    var Car = function (speed) {
      this.speed = speed;
    var my_car = new Car('40 k/h');

Functions: Scope

  • No block scope

  • Only function scope

    var foo = function () {
      var a = 3, b = 5;
      var bar = function () {
        var b = 7, c = 11;
        a += b + c;

Functions: Closure

  • Inner functions have access to outer function's parameters and variables.

    var elevator_maker = function() {
      var level = 1;
      var get_level = function() { return "level: " + level; }
      return {
        up:   function(n) { level += n; return get_level(); },
        down: function(n) { level -= n; return get_level(); },
    var elevator = elevator_maker();
    elevator.up(3);                    // level: 4
    elevator.down(1);                  // level: 3

Functions: Module

  • Can eliminate the use of global variables

    var elevator = function() {
      var level = 1;
      var get_level = function() { return "level: " + level; }
      return {
        up:   function(n) { level += n; return get_level(); },
        down: function(n) { level -= n; return get_level(); },
    elevator.up(3);                    // level: 4
    elevator.down(1);                  // level: 3

Functions: Memoization

  • Remember the results of previous operations

    var fibonacci = function (n) {
      return n < 2 ? n : fibonacci(n - 1) + fibonacci(n - 2);
    var fibonacci = function () {
      var memo = {0: 0, 1: 1};
      return function fib (n) {
        var result = memo[n];
        if (typeof result !== 'number') {
          result = fib(n - 1) + fib(n - 2);
          memo[n] = result;
        return result;
    fibonacci(10)             // 55

Inheritance: Pseudoclassical

  • Intended to look sort of object-oriented

  • Provided by using new prefix

  • Hides the true nature of the language

    var Vehicle = function(name){ this.name = name; };
    Vehicle.prototype.get_name = function(){ return this.name; };
    var vehicle = new Vehicle('Just a ride');
    var Car = function(name, racing){
      this.name = name;
      this.racing = racing;
    Car.prototype = vehicle;
    var my_car = new Car('My car', false);
    my_car.get_name();            // 'My car'
    my_car.racing;                // false

Inheritance: Prototypal

  • A new object can inherit the properties of an old object

  • Start with a useful object and then make many more like it

    var vehicle = {
      name: 'Just a ride',
      get_name: function(){ return this.name; }
    var my_car = Object.create(vehicle);
    my_car.name = 'My car'
    my_car.racing = false;
    my_car.get_name();            // 'My car'
    my_car.racing;                // false

Inheritance: Functional

  • Allows privacy

    var vehicle = function(spec) {
      spec.name = spec.name || 'Just a ride';
      var that = {};
      that.get_name = function(){ return spec.name; };
      return that;
    var car = function(spec) {
      spec.racing = !! spec.racing;
      var that = vehicle(spec);
      that.is_racing = function(){ return spec.racing; };
      return that;
    my_car = car({name: 'My car', racing: false});
    my_car.get_name();            // 'My car'
    my_car.is_racing();           // false


  • Array-like objects

  • Linked to Array.prototype

  • No linear allocated memory or computed offest access

  • Have their own literal notation

  • Elements can be of any value


  • Array literal

    var a = [];
    var misc = [ 'string', 98.6, true, null, undefined,
      ['nested', 'array'], {x: 1}, Infinity ];
  • length property is not upper bound

    var a = [];
    a.length          // 0
    a[10] = 1;
    a.length          // 11
    a[4]              // undefined
  • Have methods

    var a = [];
    a                 // [1] 

Bad parts

  • Global variables

  • No block scope

  • Semicolon insertion

      status: true
    return {
      status: true

Bad parts

  • floating point

  • Phony arrays

  • + overloading

    1 + 2               // 3
    '1' + 2             // '12'
    1 + '2'             // '12'
  • typeof

    typeof null         // object
    typeof []           // object

Bad parts

  • eval

  • Bitwise operators

  • ==

    '' == '0'          // false
    0 == ''            // true
    0 == '0'           // true
    false == 'false'   // false
    false == '0'       // true
    false == undefined // false
    false == null      // false
    null == undefined  // true
    ' \t\r\n ' == 0    // true


  • JavaScript: The Good Parts

    by Douglas Crockford

Thank You

Monday, March 30, 2009

JavaScript Code Prettifier

Writing technical blog posts about software almost always implies having to include some snippets of code to clarify your ideas, keep your target readers focused and get them to the point quickly. Even sometimes your code just happens to do all the talking. But as you always concentrate on having your thoughts coherent and your code correct you most probably miss the part where your code needs to look nice and easily read. While this can be achieved effortlessly on all current IDEs and text editors which have their syntax-highlighting property prettify your code for you, this needs some effort from you to have them look just as nice and clear on your blog articles. When looking for a tool to help me do that I came across a very nice one, the google-code-prettify project ( A Javascript module and CSS file that allows syntax highlighting of source code snippets in an html page ).

According to their README file you should do the following to have it working:

  1. Download a distribution

  2. Include the script and stylesheets in your document
    (you will need to make sure the css and js file are on your server, and
    adjust the paths in the script and link tag)

    <link href="prettify.css" type="text/css" rel="stylesheet" />
    <script type="text/javascript" src="prettify.js"></script>

  3. Add onload="prettyPrint()" to your
    document's body tag.

  4. Modify the stylesheet to get the coloring you prefer

  5. Put code snippets in <pre class="prettyprint">...</pre> or <code class="prettyprint">...</code>


This would be perfectly applicable if you own your own web server and host your blog there or if you have the blogging host allow you to upload file attachments (as the case here in our blog) for your articles and provide you with their static URLs so you can refer to them in your HTML-format article editor. But be aware that you'll have to change the extension of the file or you might not be able to upload it in most cases. e.g. if you're blogging on our blog then you can refer to this url : http://intranet.espace.com.eg/files/prettify_js.txt which I have uploaded earlier.

If that was not the case and all you've got is the HTML-format editor then you should try this way:

  1. Download a small compressed version of the prettifier.

  2. Copy the CSS text from prettify.css and paste it into a style element in your editor area.

  3. Copy the JavaScript code from prettify.js into and paste it inside a script element.

  4. Put code snippets in <pre class="prettyprint">...</pre> or <code class="prettyprint">...</code>

  5. put prettyPrint() inside a script element at the end of your editor input


Need to see it in action?

You'll get to try it your self.

Type code in the text area to the left, press the prettify button and you'll see the magic.

Type your code here:

Syntax highlighted code:

Generated HTML:

Monday, September 29, 2008

Javascript Multiple Inheritance

Since this in the body of a function is the reference to the object used to call the function e.g.

obj.setProp = function(p) { this.prop = p }
=> 5

and since Javascript constructor function is the same as any other javascript function and the only difference happens through the use of the new operator. We can use this (double meaning) to inject functionality provided by multiple constructor functions (sort of multiple inheritance) into our own objects as long as the these constructor functions are not only natively implemented (e.g. Array, String, Function, .... etc) and that the injected functionalites are not dependent on their prototypes.

function Cat() { this.scratch = function () {alert("scratch!!")} }
function Dog() { this.bite = function () {alert("bite!!")} }
var catyDog = {}
catyDog.catify = Cat
catyDog.dogify = Dog

Now the catyDog object can both scratch and bite, so you better be careful.

// alerts "scratch!!"

// alerts "bite!!"

Another way of doing the same thing but keeping the injecting functions kind of private:

function CatyDog()
var me = this
this.myownProp = 'special prop'

var init = function() {
me.catify = Cat
me.dogify = Dog
me.catify = undefined
me.dogigy = undefined

Using such technique makes it our own responsibility to select which prototype of the constructors to choose for our own constructor and also to choose non-conflicting functionality which is always the case when using multiple inheritance.

In the previous example script if either Cat or Dog constructors had a prototype set, neither catify nor dogify will set the prototype for our object. Only the new operator would do such magic. So we will have to set the prototype of our choice ourselves using __proto__ property or we can set the prototype for our constructor function and rely on the new operator magic.

Now suppose that you need CatyDog to completely inherit Dog (including its prototype) while having Cat functionality.

function CatyDog()
var me = this
this.myownProp = 'special prop'

var init = function() {
me.catify = Cat
me.catify = undefined
CatyDog.prototype = new Dog

var catyDog = new CatyDog


The difference here is that any inherited Dog property including bite function will be fetched in the prototype each time it is used.

Also here all CatyDog objects will have one single prototype Dog object.
So if you need every object to have its own prototype object can do it this way

function CatyDog()
var me = this
this.myownProp = 'special prop'

var init = function() {
me.catify = Cat
me.catify = undefined
me.__proto__ = new Dog

var catyDog = new CatyDog


Easy Application Development for the iphone

Most Developers who are new to the stormy currents of iphone development in Objective-C would stay at the shores for quite some time before they get their boats wet and start sailing.
But with Jiggy at hand, development for the iphone would be a walk in the park for most developers who are familiar with Javascript. It's really nice to use such a flexible and powerful language to script your applications.
Since Jiggy runtime wraps native Objective-C API for you. You won't even need a compiler or the tool chain to start developing. All you'll need is a browser on your machine and a jailbroken iphone with jiggy runtime and jiggy (ide) installed and you can start writing your native applications in javascript. (You can get Jiggy from here)

What you have to do

Run jiggy on your iphone, that would start its own web server that you can log on to from your browser by going to the url shown on jiggy screen and typing the user name and password (both are "jiggy" initially)
Now you can write, save and run your application form your browser ide.

What actually happens

Running the application actually runs a 17K bootstrap executable called jiggy (of course) which is included with every Jiggy application you write. this executable loads the Jiggy runtime and evalutes and executes your javascript code which should be in main.js file.
Jiggy Runtime is a collection of Jigglins ( Objective-C dynamic libraries that expose part of the Objective-C API to Javascript)
Jiggy Runtime can be extended by building new Jigglins that expose more of the native API.

An example

A Hello world marquee application.

// main.js
Plugins.load( "UIKit" );
include( "marquee.js" )
var window = new UIWindow( UIHardware.fullScreenApplicationContentRect );
window.setHidden( false );
window.backgroundColor = [ 1 , 1 , 1 , 1 ];
var mainView = new UIView();
window.setContentView( mainView );
var bounds = [0,0,window.bounds[2],20]
var delay = 4
var marquee = new Marquee( "Hello World", mainView, bounds, delay )
marquee.onStop = function() { marquee.start() }

Well since the UIKit plugin does not provide Marquee constructor I had to write one myself and include it before using it in main.js.
But the good news is I wrote it in Javascript.

I made use of components already provided by the UIKit plugin namely UIScroller, UITextLabel, UIFrameAnimation and Animator.

Here's the trick.

A UITextLabel holds the text and using an animation it crosses the width of it's container view, a UIScroller.

The animation starts with the text label totally hidden beyond the right border of the scroller and stops when it totally disappears beyond the left border.

The delay passed to UIFrameAnimator should be the total time of the animation in seconds.

So that delay for the Marquee, the time taken by text in the marquee to cross the width of the scroller, had to be corrected before passing it to the animation constructor.
If you're interested here's the source.

// marquee.js
function Marquee(text, parent, bounds, delay, onStop) {
var me = this
var scroller = new UIScroller(bounds)
var label = new UITextLabel([bounds[2], 0, bounds[2], bounds[3]])
label.text = text
var startFrame = label.frame
startFrame[2] = label.textSize[0]
label.frame = startFrame
this.delay = delay ? delay : 10
this.onStop = onStop ? onStop : null
var scroll
var correctDelay = function(delay) {
var w = scroller.bounds[2]
return delay * (label.frame[2] + w) / w
this.start = function() {
var endFrame = startFrame
endFrame[0] = -endFrame[2]
scroll = new UIFrameAnimation( label , 3, startFrame , endFrame )
scroll.onStop = this.onStop
Animator.addAnimation(scroll, correctDelay(me.delay), true)

If you're interested in a more complete Marquee constructor check this one out.

Tuesday, July 17, 2007

Java vs. C++ - Part Two

These are some more differences between Java and C++.

Class attributes and behaviors Attributes are "instance variables".
Behaviors are "methods"
Attributes are "data members".
Behaviors are "member functions"
Extending Class Object Every class is a subclass of Object and so inherits the 11 methods defined by class object, you never create a class from scratch. Even if a class doesn't explicitly use extends in its definition, it implicitly extends Object You can create classes from scratch. A class will inherit attributes and behaviors of a base class ONLY when its declaration explicitly implies that it should.
Packages Every class belongs to a package even if not explicitly specified it will be the default package ( the current directory ) Classes do not have packages. Their containing header files are simply included in source files in which they are to be used
Constructor name Methods other than the constructor of a class ARE ALLOWED to have the same name as the class AND to specify return types but these are not constructors and won't be called when an object is created. It is NOT ALLOWED for any member function other than the constructor to have the same name as the class name AND it is INVALID to specify a return type for any constructor.
Initializing attributes Instance variables CAN be initialized where they are declared IN THE CLASS BODY, by the class's constructor, or they can be assigned values by "set" methods. Instance variables that are not explicitly initialized by the programmer are initialized by the compiler (primitive numeric variables are set to 0, booleans are set to false and references are set to null). Data members can be initialized ONLY by the class's constructor, or they can be assigned values by "set" methods. Instance variables that are not explicitly initialized by the programmer are NOT automatically initialized (they will have whatever values that happened to be stored in their allocated memory space).
Accessing hidden attributes An instance variable hidden by a local variable (having the same name) can be accessed in a method by:
(this is a reference to the current object)
Such a hidden data member can be accessed in the member function by:
(this here is a pointer to the current object)
Access modifiers Each instance variable or method declaration in a Class definition must be preceded by an access modifier. Access modifiers are followed by a colon and apply to all following member declarations until overridden by another access modifier. If they were omitted they are implicitly applied by the compiler:
for classes: members are private by default.
for structs: members are public by default.
Package access Members that have no access modifier preceding their declaration are accessible to all the classes included in the same package. Members are either public or private and the only way that another class could access a non-public member of a different class is by inheritance of protected members or by being declared as a friend class of that class.
Memory leaks Are less likely to occur because Java performs automatic garbage collection to help return memory back to the system. When an object is no longer used in a program ( there are no references to the object e.g. if null was assigned to the objects reference ) it is marked for garbage collection. Before the garbage collector returns memory resources to the system it calls the finalize method of the object to be destroyed. Are common because memory is not automatically reclaimed to the system it is the programmer's responsibility to do that himself by freeing the memory in the Class destructor when its task is over.
Multiple inheritance Is not supported but interfaces are supported that allow a class to acquire multiple functionalities from any number of interfaces Is supported.
Over-ridden superclass methods Can be accessed from the subclass by:
Such an over-ridden base-class member function can be accessed by the derived class by:
Calling superclass constructor To explicitly call the superclass Parent constructor from the subclass Child constructor:
public Child( int a, int b )
super( a );
x = b;
The calling statement must be the first statement in the subclass constructor
To do the same thing here it goes like this:
Child( int a, int b )
: Parent( a )
x = b;
here we use the member initializer ( : ) to call the Parent constructor before the body of the constructor is executed
Polymorphism and dynamic binding Applies automatically.
When a reference to a subclass object is assigned to a superclass reference which is then used to invoke a superclass method that is overridden in the subclass definition the java compiler only checks that the class of the reference really has that method and the java interpreter calls the method of the actual data type of the object at execution time.
Does NOT apply automatically.
When a pointer to a derived-class object is assigned to a base-class pointer which is then used to invoke a base-class member function that is overridden in the derived class definition the compiler treats the object exactly as an object of the base-class and the base-class member function is called for the object. This is overcome by declaring the function to be a vertual one and in this case the compiler generates code that would at run time access the appropriate version of the function for the actual object's data type.
final methods and final classes

A method that is declared final cannot be overridden in a subclass.

A class that is declared final cannot be a superclass( cannot have subclasses).

Does not have an equivalent in C++
const functions Java has no equivalent for C++'s const functions A member function can be declared as const, indicating that calling that member function does not change the object.
Abstract classes Are declared by using abstract and have one or more abstract mehtods
public abstract ClassName {
private int instanceVariable;
public int someMethod1()....
public void someMethod2()...
public abstract int method();
//abstract method
Must have one or more pure virtual functions
class ClassName {
virtual int someFunction1()...
virtual int someFunction2()...
virtual int function() = 0;
// pure virtual funtion
int dataMember;
GUI support Normally has packages that support frames, windows, Graphical User Interface components. Does not normally support them. Appropriate third party libraries must be obtained to offer their support.

Thursday, June 28, 2007

Java vs. C++ - Part One

Java vs. C++ - Part One

These are only some of the differences between Java and C++ that I found so far that drew my attention and I think are worth mentioning.

Compiling source codeWhen we compile a source file a .class file is generated in java byte-codes ( machine independent = portability ) that is not translated into machine language instructions until in the run time when interpreted by the Java Virtual Machine
( machine dependent ).
A source file is compiled and linked to produce an .exe file in machine language that is ready to be executed when the file is loaded into memory and run by the operating system.
Function definitions All function definitions and variable declarations are inside Classes even main(). Nothing is allowed to be outside a class except imports and package names.Function definitions are outside class definitions. They have prototypes whose place decides function scope
Including classesImporting a package.* just directs the compiler to the location of classes used in the code so that only these classes are included not the whole package. while in C++ I think that including a header file means that all classes in that header file will be compiled and linked to the source file.
Ending class definitionsClass definitions end with } without a semicolon.Class definitions end with };
Creating objectsAll objects must be created with new, so they are all dynamically allocated in the heap.
Only primitive data types can be allocated on the stack.
Objects can also be created and allocated without new so they are put on the stack in the scope of their declaration.
Declaring a reference:Declaring a reference to an object without using new to allocate the object only reserves space for the reference and no object is created in memory until new is used and the resulting object is given to the reference to point to it.Declaring an object without initializing it makes the compiler call the default constructor for the object's class and memory is allocated for the object in the stack.
Calling static methodsClassName.methodName( args.. );ClassName::functionName( args.. );
or ObjectName.functionName( args..);
Wrapper classesJava has wrapper classes for primitive data types that contains static methods for handling them
e.g. String string = Integer.toString( intVariable );
C++ doesn't normally have them in its standard libraries
Array declaration and memory allocation:An array is considered an object that has to be allocated by new.
   int c[];

declares the array reference

   c = new int[ 12 ];

allocates the array and automatically initialize its elements to zero for numeric primitive types, false for boolean, null for references ( non-primitive types)

   int c[] = new int[ 12 ];
// in one step

you can never specify the number of elements in the [] in a declaration unlike C++.

For multiple array declarations:

   double a[], b[];     

a = new double[ 100 ];
b = new double[ 27 ];


double a[] = new double[ 100 ],
b[] = new double[ 27 ];
double[] a, b;

a = new double[ 100 ];
b = new double[ 27 ];


double[] a = new double[ 100 ],
b = new double[ 27 ];

Elements of an array of a primitive data type contain values of that data type.
While elements of an array of a non-primitive data type contian "references" to objects of that data type.

( they have the value null by default )

Allocating and initializing arrays in declarations:

   int n[] = { 32, 27, 64, 18, 95,
14, 90, 70, 60, 37 };
// initializer list

Array size is determined by the number of elements in the list. Here new operator is provided by the compiler and the array object is also dynamically allocated.

When a Java program is executed. the Java interpreter checks array element subscripts to be sure they are valid. If there is an invalid subscript, Java generates an exception: ArrayIndexOutOfBoundsException.

   int c[ 12 ];

declares and allocated memory for 12 int elements without initializing them also memory is not dynamically allocated but instead it is preserved from the start and is allocated in the stack I presume.
For multiple array declaration:

   double a[ 100 ],
b[ 27 ];

Elements of an array of any data type contain values or objects of that data type.
Objects for which an array can be declared must have a default constructor to be called for every element when the array is declared.

initializing arrays in declarations:

   int n[ 10 ] = { 0 };

initialize elements of array n to 0

   int n[] = { 1, 2, 3, 4, 5 };

array size determined by the number of elements in the list

No checking for array bounds is done by the compiler so the programmer must be very carful not to exceed the array length

Multiple subscripted arrays

Doesn't directly support multiple-subscripted arrays but allows the programmer to specify single-subscripted arrays whose elements are also single-subscripted arrays, achieving the same effect.
i.e. arrays of arrays:

   int b[][] = { { 1, 2 },
{ 3, 4, 5 } };

b[ 0 ] is a reference to an array of 2 elements
b[ 1 ] is a reference to an array of 3 elements

   int b[][];
b = new int[ 3 ][ 3 ];

3 by 3 array allocated

   int b[][];
b = new int[ 2 ][];

allocates rows

   b[ 0 ] = new int[ 5 ];

allocates columns for row 0

   b[ 1 ] = new int[ 3 ];

allocates columns for row 1

Directly supports multiple-subscripted arrays and their elements are placed consecutively in memory row after row and the elements are actually located by pointer arithmetic.

   int b[][] = { { 1, 2 },
{ 3, 4, 5 } };

causes an error in C++ "error: declaration of 'b' as multidimensional array must have bounds for all dimensions except the first."

   int b[][ 3 ] = { { 1, 2 },
{ 3, 4, 5 } };

declares and preserves memory for a 2 by 3 multidimensional array b and initializes missing element in the list b[ 0 ][ 2 ] by 0.

Passing arguments

Java does not allow the programmer to decide whether to pass an argument call-by-value or call-by-reference:
Primitive data type variables are always passed call-by-value.
Objects are not passed to methods; references to objects are passed
(call-by-value just like pointers in C++ are) so the method can manipulate the object directly.

You can pass primitive data types or objects either call-by-value or call-by-reference ( using pointers or references to them ).


When returning information from a method via a return statement:

Primitive data type variables are always returned by value (a copy is returned).
Objects are always returned by reference - a reference to the object is returned.

Objects and primitive data type variables can be returned by value or by reference

Constant variables

Constant variables ( read only variables ) are declared using final.

They are declared using const.

Wednesday, May 23, 2007

Virtual functions in C++

"In order to implement the concept of Polymorphism which is a corner-stone of OOP the C++ compiler has to find a way to make it possible."

Lets see how the story begins.

Derived classes inherit member functions of the base class but when some member functions are not exactly appropriate for the derived class they should provide their own version of these functions to override the immediate base class' functions and make their own objects happy. So if any of these functions is called for a derived object the compiler calls its class' version of that function.

This works quite fine when the types of objects are known at compile time so that the compiler knows which function to call for each particular object. The compiler knows where to find the copy of the function for each class and so the addresses used for these function calls are
settled at compile time. ( static binding )

Suppose that we have a lot of derived objects at different levels of the inheritance hierarchy that have a common base class and that they need to be instantiated at run time. Here the compiler does not know in advance what derived class objects to expect. These objects would be dynamically allocated and the code for handling these objects should be able to deal with all them.

It is perfectly legitimate to use base class pointers to point to these objects but that requires the compiler to handle them exactly the same way they would handle their base class objects. So they would call base class versions of member functions and none of the member functions specific for the derived class would be accessible.

To solve this problem
Virtual functions are used to allow dynamic binding.

"...It seems that our friend, the compiler of course, is very resourceful."

To support Polymorphism at runtime the compiler builds at compile time
virtual function tables ( vtables ). Each class with one or more virtual functions has a vtable that contains pointers to the appropriate virtual functions to be called for objects of that class. Each object of a class with virtual functions contains a pointer to the vtable for that class which is usually placed at the beginning of the object.

The compiler then generates code that will:

1. dereference the base class pointer to access the derived class object.
2. dereference its vtable pointer to access its class vtable.
3. add the appropriate offset to the vtable pointer to reach the desired function pointer.
4. dereference the function pointer to execute the appropriate function.

This allows dynamic binding as the call to a virtual function will be
routed at run time to the virtual function version appropriate for the class.

Impressive isn't it?

Well that made me try just for fun to write code that would do these steps instead of the compiler.

But as I did this another question evolved.

How does member functions get their "this" pointer ? ( pointer to the object the function is called for )

I know that the compiler should implicitly pass 'this' as an argument to the member function so that it can use it to access data of the object it is called for.

I used in my example a single virtual function that takes no arguments and returns void.
So at first I tried calling the destination virtual function with no arguments. The function was called already but the results showed it has used some false value for 'this' that pointed it somewhere other than the object and gave the wrong results.

So I tried calling the function and passing it the pointer to the object and it seemingly worked just fine.

Here's the code I tried...

#include <iostream>

using std::cout;
using std::endl;

class Parent {
   Parent( int = 0, int = 0 );  // default constructor
   void setxy( int, int );
   int getx() const { return x; }
   int gety() const { return y; }
   virtual void print();
   int x;
   int y;

Parent::Parent( int a, int b )
   setxy( a, b );

void Parent::setxy( int a, int b )
   x = ( a >= 0 ? a : 0 );
   y = ( b >= 0 ? b : 0 );

void Parent::print()
   cout << " [ x: " << a =" 0," b =" 0," c =" 0" d =" 0" z =" (">= 0 ? c : 0 );
   t = ( d >= 0 ? d : 0 );

void Child::print()
   cout << " [ z: " << int =" 0," int =" 0," int =" 0," int =" 0," int =" 0);" e =" (">= 0 ? num : 0 );

void GrandChild::print()
   cout << " [ e: " << e << " ]";

int main()
   Parent parentObj( 7, 8 );
   Child childObj( 56, 23, 6, 12 );
   GrandChild grandchildObj( 4, 64, 34, 98, 39 );
   // declare an array of pointers to Parent
   Parent *parentPtr[ 3 ];          

   cout << "size of Parent = " << sizeof( Parent ) << " bytes\n";
   cout << "size of Child = " << sizeof( Child ) << " bytes\n";
   cout << "size of GrandChild = "
        << sizeof( GrandChild ) << " bytes\n";

   parentPtr[ 0 ] = &parentObj;      // direct assignment
   parentPtr[ 1 ] = &childObj;       // implicit casting
   parentPtr[ 2 ] = &grandchildObj;  // implicit casting

   cout << "\nThe Derived objects accessed by"
         " an array of pointers to Parent:\n\n";

   for ( int i = 0; i < 3; i++ ) {
      cout << "Object " << i + 1 << " : ";
      cout << "\tvtable ptr (" << *( ( void ** ) parentPtr[ i ] ) << ")\n" ;
                  // vtable ptr at the beginning of the object
      // initialize pointer to function
      void (* funptr ) ( Parent * ) = NULL;       

      // assign to it pointer to function in vtable    
      funptr = *( *( ( void (*** ) ( Parent * ) ) parentPtr[ i ] ) );
      cout << "\t\tpointer 1 in vtable is (" << ( void * ) funptr
           << ")\n\t\t( pointer to virtual function 1 'print()' )";

      cout << "\n\n\t\tdata: ";

      funptr( parentPtr[ i ] ); // call the 1st function in vtable
                               // and passing ( this ) to it
                              // without using parentPtr[ i ]->print();
      cout << "\n" << endl;

   return 0;
The output should look like this:

size of Parent = 12 bytes
size of Child = 20 bytes
size of GrandChild = 24 bytes

The Derived objects accessed by an array of pointers to Parent:

Object 1 : vtable ptr (0043FD90)
pointer 1 in vtable is (00401480)
( pointer to virtual function 1 'print()' )

data: [ x: 7, y: 8]

Object 2 : vtable ptr (0043FD80)
pointer 1 in vtable is (004015B8)
( pointer to virtual function 1 'print()' )

data: [ x: 56, y: 23] [ z: 6, t: 12]

Object 3 : vtable ptr (0043FD70)
pointer 1 in vtable is (004016E6)
( pointer to virtual function 1 'print()' )

data: [ x: 4, y: 64] [ z: 34, t: 98] [ e: 39 ]

In order to reach the function pointer to the desired function ( print() ) the parentPtr of the object which normally points to its beginning had to be casted to type pointer to pointer to pointer to function before it was dereferenced to give the vtabel pointer and then dereferenced again to give the first pointer to function in the vtable.

Polymorphism uses virtual functions in another interesting way. Virtual functions enables us to create special classes for which we never intend to instantiate any objects. These classes are called abstract classes and they only used to provide an appropriate base class that passes a common interface and/or implementation to their derived classes.

Abstract classes are not specific enough to define objects. Concrete classes on the other hand have the specifics needed to have a real object. To make a base class abstract it must have one or more pure virtual functions which are those having = 0 added at the end of its function prototype.

virtual void draw() const = 0;

These pure virtual functions should be all overridden in the derived classes for these to be concrete ones or else they would be abstract classes too.

Suppose we have a base class Hardware. We can never draw, print the production date or price unless we know the exact type of hardware we're talking about. So it looks that class Hardware could make a good example for an abstract base class.

Another example could be class Furniture and it might look something like this:

Class Furniture {
// ...
   virtual double getVolume() const = 0; // a pure virtual
   virtual void draw() const = 0;       // another one here
// ...               

Here class Furniture definition contains only the interface and implementation to be inherited.
It even does not contain any data members.

That's it.
Hope you liked this article.

I will be happy to receive your comments.