tag:blogger.com,1999:blog-78186761958594882702023-11-15T09:47:53.824-08:00mshalabymshalabyhttp://www.blogger.com/profile/13133192118777632030noreply@blogger.comBlogger7125tag:blogger.com,1999:blog-7818676195859488270.post-33593276802283832122012-05-15T02:47:00.002-07:002012-05-15T03:24:20.953-07:00Introduction to JavaScript<div dir="ltr" style="text-align: left;" trbidi="on">
<style>pre.prettyprint{padding:2px;border:1px solid #888} .str { color:#181; font-style:italic } .kwd { color:#369; font-weight:bold } .com { color:#666 } .typ { color:#c40 } .lit { color:#900 } .pun { color:#000; font-weight:bold } .pln { color:#333 } .tag { color:#369; font-weight:bold } .atn { color:#939; font-weight:bold } .atv { color:#181 } .dec { color:#606 }.slide{margin-top: 50px;}</style><br /><br /><script src="http://www.gstatic.com/codesite/ph/14407163836014391775/js/prettify/prettify.js"></script>
<div class="deck-container">
<div>
<p>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.</p>
<p>I'll be visiting the content and adding more clarification soon.</p>
</div>
<!-- Begin slides -->
<section class="slide" id="name">
<h2>The Name: JavaScript</h2>
<ul>
<li class="slide" id="name-prefix">
<h3>Prefix: Java</h3>
<p>Is it related to Java? A subset maybe?</p>
<h3>No</h3>
<p>It has nothing to do with Java</p>
</li>
<li class="slide" id="name-suffix">
<h3>Suffix: Script</h3>
<p>Is it just a scripting language?</p>
<p>Not a real programming language?</p>
<h3>No</h3> <p>It is a complete programming language</p>
</li>
</ul>
</section>
<section class="slide" id="popularity">
<h2>Popularity</h2>
<ul>
<li><h3>Available in all browsers</h3></li>
<li><h3>The most popular programming language</h3></li>
</ul>
</section>
<section class="slide" id="misunderstood">
<h2>The Most Misunderstood Programming Language</h2>
<ul>
<li><h3>The name</h3><p>prefix and suffix</p></li>
<li><h3>It is different</h3><p>Programmers don't even bother to learn it</p></li>
<li><h3>Unfairly blamed for the awfulness of the DOM</h3></li>
<li><h3>Previous bad implementations</h3></li>
<li><h3>Lack of good books</h3></li>
</ul>
</section>
<section class="slide" id="design-good">
<h2>Design: Very Good Ideas</h2>
<ul>
<li><h3>Functions are first class objects</h3><p>They can be passed as arguments and return values</p></li>
<li><h3>Loose Typing</h3><p>Easier - more expressive</p></li>
<li><h3>Dynamic Objects</h3><p>General containers = hash tables</li>
<li><h3>Object Literal Notation</h3><p>Very expressive</p></li>
</ul>
</section>
<section class="slide" id="design-controversial">
<h2>Design: Controversial Ideas</h2>
<ul>
<li><h3>Prototypal Inheritance</h3><ul>
<li><h4>No Classes</h4></li>
<li><h4>Objects inherit directly form other objects</h4></li>
<li><h4>Very powerful</h4></li>
<li><h4>Not commonly understood very well</h4></li>
</ul></li>
</ul>
</section>
<section class="slide" id="design-bad">
<h2>Design: Very Bad Ideas</h2>
<ul>
<li><h3>Linkage through global variables</h3>
<ul>
<li><h4>Compilation units (scipt tags) are combined in a commmon global namespace</h4></li>
<li><h4>Variables can collide</h4></li>
</ul>
</li>
</ul>
</section>
<section class="slide" id="types">
<h2>Types (Values)</h2>
<ul>
<li><h3>Simple types</h3>
<ul>
<li><h4>Numbers</h4></li>
<li><h4>Strings</h4></li>
<li><h4>Booleans</h4></li>
<li><h4>null</h4></li>
<li><h4>undefined</h4></li>
</ul>
</li>
<li><h3>Objects</h3></li>
</ul>
</section>
<section class="slide" id="numbers">
<h2>Numbers</h2>
<ul>
<li><h3>Only one number type</h3></li>
<li><h3>64-bit floating point (same as Java's double)</h3>
<pre><code class="prettyprint">0.1 + 0.2 // 0.30000000000000004</code></pre>
</li>
<li><h3>100, 100.0, 1e2 are equivalent</h3></li>
<li><h3>NaN and Infinity are special numbers</h3></li>
</ul>
</section>
<section class="slide" id="numbers-nan">
<h2>Numbers: NaN</h2>
<ul>
<li><h3>Special Number: Not a Number</h3></li>
<li><h3>Result of erroneous operations</h3>
<pre><code class="prettyprint">2 * 'a' // NaN</code></pre>
</li>
<li><h3>Toxic</h3>
<pre><code class="prettyprint">5 + NaN // NaN</code></pre>
</li>
<li><h3>Not equal to any value (including itself)</h3>
<pre><code class="prettyprint">NaN == NaN // false
isNaN(NaN) // true</code></pre>
</li>
</ul>
</section>
<section class="slide" id="numbers-infinity">
<h2>Numbers: Infinity</h2>
<ul>
<li><h3>Special Number</h3>
<pre><code class="prettyprint">1 / 0 // Infinity
1 / Infinity // 0</code></pre>
</li>
<li><h3>Represents numbers > <code>1.79769313486231570e+308</code></h3>
<pre><code class="prettyprint">1.8e308 // Infinity</code></pre>
</li>
</ul>
</section>
<section class="slide" id="numbers-number">
<h2>Numbers: Number function</h2>
<ul>
<li><h3>Converts a value into a number</h3>
<pre><code class="prettyprint">Number('') // 0
Number('0032') // 32
Number('123abc') // NaN
Number('abc') // NaN</code></pre>
</li>
<li><h3>So does the '+' prefix operator</h3>
<pre><code class="prettyprint">+'' // 0
+'0032' // 32
+'123abc' // NaN
+'abc' // NaN</code></pre>
</li>
</ul>
</section>
<section class="slide" id="numbers-parse">
<h2>Numbers: parseInt</h2>
<ul>
<li><h3>Also converts a value into a number</h3></li>
<li><h3>Stops at first non-digit character</h3>
<pre><code class="prettyprint">parseInt('123abc', 10) // 123</code></pre>
</li>
<li><h3>If no radix is passed it defaults to 10 (8 if input starts with 0)</h3>
<pre><code class="prettyprint">parseInt('32') // 32 (as decimal)
parseInt('0032') // 26 (as octal if starts with 0)
</code></pre>
</li>
<li><h3>Always specify the radix</h3>
<pre><code class="prettyprint">parseInt('0032', 10) // 32
parseInt('0032', 8) // 26
</code></pre>
</li>
</ul>
</section>
<section class="slide" id="numbers-parse">
<h2>Numbers: Math</h2>
<ul>
<li><h3>An object containing methods that act on numbers</h3>
<p>abs, acos, asin, atan, atan2, ceil, cos, exp, floor, log, max, min, pow, random, round, sin, sqrt, tan</p>
<pre><code class="prettyprint">Math.floor(12.53) // 12</code></pre>
</li>
<li><h3>Also contains some useful constants</h3>
<p>E, LN10, LN2, LOG10E, LOG2E, PI, SQRT1_2, SQRT2</p>
<pre><code class="prettyprint">Math.PI // 3.141592653589793</code></pre>
</li>
</ul>
</section>
<section class="slide" id="strings">
<h2>Strings</h2>
<ul>
<li><h3>0 or more 16-bit characters</h3></li>
<li><h3>A character is just a String of length 1</h3></li>
<li><h3>Immutable</h3></li>
<li><h3>String literal</h3>
<pre><code class="prettyprint">'abc' == "abc" // true</code></pre>
</li>
<li><h3>length property (number of 16-bit characters)</h3>
<pre><code class="prettyprint">'abc'.length // 3</code></pre>
</li>
</ul>
</section>
<section class="slide" id="strings-2">
<h2>Strings</h2>
<ul>
<li><h3>Concatenating</h3>
<pre><code class="prettyprint">'Java' + 'Script' // 'JavaScript'</code></pre>
</li>
<li><h3>String function</h3>
<pre><code class="prettyprint">String(123) // '123'</code></pre>
</li>
<li><h3>Strings have methods</h3>
<pre><code class="prettyprint">'cat'.toUpperCase() // 'CAT'</code></pre>
</li>
</ul>
</section>
<section class="slide" id="boolean">
<h2>Boolean</h2>
<ul>
<li><h3>true - false</h3></li>
<li><h3>Boolean function</h3>
<pre><code class="prettyprint">Boolean(truthy_value) // true</code></pre>
</li>
<li><h3>!! prefex operator</h3>
<pre><code class="prettyprint">!! falsy_value // false</code></pre>
</li>
</ul>
</section>
<section class="slide" id="null-undefined">
<h2>null</h2>
<ul>
<li><h3>A value that is not anything</h3></li>
</ul>
<h2>undefined</h2>
<ul>
<li><h3>A value that is not even a value</h3></li>
<li><h3>The default value for variables and parameters</h3></li>
<li><h3>The value of missing members of an object</h3></li>
</ul>
</section>
<section class="slide" id="falsy-values">
<h2>Falsy values</h2>
<ul>
<li><h3>6 possible falsy values</h3>
<pre><code class="prettyprint">!! false // false
!! null // false
!! undefined // false
!! '' // false
!! 0 // false
!! NaN // false</code></pre>
</li>
<li><h3>All other values are truthy</h3>
<pre><code class="prettyprint">!! '0' // true</code></pre>
</li>
</ul>
</section>
<section class="slide" id="objects">
<h2>Objects</h2>
<ul>
<li><h3>An object is a container of properties</h3></li>
<li><h3>A property has a name (string) and value (any type)</h3></li>
<li><h3>Class-free (No constraints on names/values of new properties)</h3></li>
<li><h3>Objects are hash tables</h3></li>
<li><h3>Protype linkage</h3></li>
<li><h3>Arrays, functions, regular expressions and objects are objects</h3></li>
</ul>
</section>
<section class="slide" id="object-literal">
<h2>Objects: Object literal</h2>
<ul>
<li><h3>Very convenient for creating new object values</h3></li>
<li><h3>A pair of curly braces surrounding 0+ name/value pairs</h3>
<pre><code class="prettyprint">var empty_object = {};</code></pre>
<pre><code class="prettyprint">var person = { 'first-name': 'John' };</code></pre>
<pre><code class="prettyprint">var city = {
name: 'Alexandria',
location: { latitude: 31.2, longitude: 29.9 }
};</code></pre>
</li>
</ul>
</section>
<section class="slide" id="object-retrieval">
<h2>Objects: Retrieval</h2>
<ul>
<li><h3>Subscript notation</h3>
<pre><code class="prettyprint">person['first-name'] // 'John'
city['name'] // 'Alexandria'</code></pre>
</li>
<li><h3>Dot notation</h3>
<pre><code class="prettyprint">city.name // 'Alexandria'
city.location.latitude // 31.2</code></pre>
</li>
<li><h3>Missing properties</h3>
<pre><code class="prettyprint">person.nickname // undefined</code></pre>
</li>
</ul>
</section>
<section class="slide" id="object-retrieval-2">
<h2>Objects: Retrieval</h2>
<ul>
<li><h3>|| operator (set default values)</h3>
<pre><code class="prettyprint">var name = person.nickname || 'anonymous'; // 'anonymous'</code></pre>
</li>
<li><h3>&& operator (handle missing nested objects)</h3>
<pre><code class="prettyprint">city.country // undefined
city.country.name // throws a TypeError
city.country && city.country.name // undefined</code></pre>
</li>
</ul>
</section>
<section class="slide" id="object-update">
<h2>Objects: Update</h2>
<ul>
<li><h3>Simply by assignment</h3>
<pre><code class="prettyprint">person['first-name'] = 'Thomas'; // Replaced 'first-name'</code></pre>
<pre><code class="prettyprint">person['last-name'] = 'Anderson'; // Added 'last-name'</code></pre>
</li>
</ul>
</section>
<section class="slide" id="object-reference">
<h2>Objects: Reference</h2>
<ul>
<li><h3>Objects are passed around by reference</h3>
<pre><code class="prettyprint">var x = person; // x & person refer to the same object
x.nickname = 'Neo';
person.nickname // 'Neo'
</code></pre>
<pre><code class="prettyprint">var a = {}, b = {}, c = {}; // different empty objects</code></pre>
<pre><code class="prettyprint">var a = b = c = {}; // the same empty object</code></pre>
</li>
</ul>
</section>
<section class="slide" id="object-prototype">
<h2>Objects: Prototype</h2>
<ul>
<li><h3>Every object is linked to a prototype object</h3></li>
<li><h3>Objects created by object literal are linked to Object.prototype</h3>
<pre><code class="prettyprint">Object.prototype.foo = 'bar';
var a = {}, b = {};
a.foo // 'bar'
b.foo // 'bar'
</code></pre>
</li>
<li><h3>Protype link is used only for retrieval (prototype chain)</h3>
<pre><code class="prettyprint">a.foo = 'blah'; // Added foo property to a
a.foo // 'blah'
b.foo // 'bar'
</code></pre>
</li>
</ul>
</section>
<section class="slide" id="object-prototype-2">
<h2>Objects: Prototype</h2>
<ul>
<li><h3>We can specify the prototype for a new object</h3></li>
<li><h3>Complex but simplified by <code>Object.create</code> function (in new JS editions)</h3>
<pre><code class="prettyprint">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'
</code></pre>
</li>
</ul>
</section>
<section class="slide" id="object-refelection">
<h2>Objects: Reflection</h2>
<ul>
<li><h3>hasOwnProperty</h3>
<pre><code class="prettyprint">Object.prototype.foo = 'bar';
var a = {foo: 'blah'}, b = {};
a.foo // 'blah'
b.foo // 'bar'
a.hasOwnProperty('foo') // true
b.hasOwnProperty('foo') // false
</code></pre>
</li>
</ul>
</section>
<section class="slide" id="object-enumeration">
<h2>Objects: Enumeration</h2>
<ul>
<li><h3>for in</h3>
<pre><code class="prettyprint">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</code></pre>
</li>
</ul>
</section>
<section class="slide" id="object-delete">
<h2>Objects: Delete</h2>
<ul>
<li><h3><code>delete</code> removes a property from an object</h3>
<pre><code class="prettyprint">delete person.age;
person.age // undefined</code></pre>
</li>
<li><h3>May let a prototype property shine through</h3>
<pre><code class="prettyprint">person['first-name'] = 'Jason';
person['first-name'] // 'Jason'
delete person['first-name']
person['first-name'] // 'John'</code></pre>
</li>
</ul>
</section>
<section class="slide" id="object-global-abatement">
<h2>Objects: Reducing Global Footprint</h2>
<ul>
<li><h3>A single global variable for your application</h3>
<pre><code class="prettyprint">var MyAPP = {};</code></pre>
</li>
<li><h3>Contains all your variables (as properties)</h3>
<pre><code class="prettyprint">MyAPP.someone = {'first-name': 'John', 'last-name': 'Doe'};
MyApp.person = Object.create(MyAPP.someone);</code></pre>
</li>
</ul>
</section>
<section class="slide" id="functions-objects">
<h2>Functions</h2>
<ul>
<li><h3>The best thing in JavaScript</h3></li>
<li><h3>A function encloses a set of statements that execute when invoked</h3></li>
<li><h3>Functions are objects</h3>
<ul>
<li><h4>Linked to a prototype (Function.prototype)</h4></li>
<li><h4>Can be stored in variables, objects, and arrays</h4></li>
<li><h4>Can be passed as arguments to functions and can be returned from functions</h4></li>
</ul>
</li>
<li><h3>A function has a prototype property</h3></li>
<li><h3>Uses:</h3>
<ul>
<li><h4>Code reuse, Information hiding, Composition</h4></li>
</ul>
</li>
</ul>
</section>
<section class="slide" id="functions-function-literal">
<h2>Functions: Function Literal</h2>
<ul>
<li><h3>4 parts:</h3>
<ol>
<li><h4>function (reserved word)</h4></li>
<li><h4>name (optional)</h4></li>
<li><h4>parameters</h4></li>
<li><h4>body</h4></li>
</ol>
<pre><code class="prettyprint">var add = function (a, b) {
return a + b;
};</code></pre>
</li>
</ul>
</section>
<section class="slide" id="functions-invocation">
<h2>Functions: Invocation</h2>
<ul>
<li><h3>Extra parameters: <code>this</code> & <code>arguments</code></h3></li>
<li><h3>Invocation Patterns</h3>
<ol>
<li><h4>Method invocation pattern</h4></li>
<li><h4>Function invocation pattern</h4></li>
<li><h4>Constructor invocation pattern</h4></li>
<li><h4>Apply invocation pattern</h4></li>
</ol>
</li>
<li><h3>Arguments</h3>
<ul>
<li><h4>No error if not matching number of parameters</h4></li>
<li><h4>Extra arguments are ignored</h4></li>
<li><h4>Missing will be <code>undefined</code></h4></li>
</ul>
</li>
</ul>
</section>
<section class="slide" id="functions-method">
<h2>Functions: Method Invocation Pattern</h2>
<ul>
<li><h3>Function is stored as a property of an object</h3></li>
<li><h3><code>this</code> will be the object</h3>
<pre><code class="prettyprint">var myObject = {
value: 0,
increment: function (inc) {
this.value += inc;
}
};
myObject.increment(2);
myObject.value; // 3</code></pre>
</li>
</ul>
</section>
<section class="slide" id="functions-function">
<h2>Functions: Function Invocation Pattern</h2>
<ul>
<li><h3>Function is not a property of an object</h3></li>
<li><h3><code>this</code> will be the global object (design mistake)</h3>
<pre><code class="prettyprint">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</code></pre>
</li>
</ul>
</section>
<section class="slide" id="functions-constructor">
<h2>Functions: Constructor Invocation Pattern</h2>
<ul>
<li><h3>Invoked with <code>new</code> prefix</h3></li>
<li><h3>A new object is created & linked to function's prototype property</h3></li>
<li><h3><code>this</code> is bound to the new object</h3>
<pre><code class="prettyprint">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
</code></pre>
</li>
</ul>
</section>
<section class="slide" id="functions-apply">
<h2>Functions: Apply Invocation Pattern</h2>
<ul>
<li><h3><code>apply</code> is a method of functions</h3></li>
<li><h3>2 parameters: value for <code>this</code> & array of arguments</h3>
<pre><code class="prettyprint">var util = {
get_status: function(uppercase){
return uppercase ?
this.status.toUpperCase() : this.status;
}
};
var obj = { status: 'ok' };
util.get_status.apply(obj, [true]); // 'OK'</code></pre>
</li>
</ul>
</section>
<section class="slide" id="functions-arguments">
<h2>Functions: Arguments</h2>
<ul>
<li><h3><code>arguments</code>: array of parameters passed to a function</h3></li>
<li><h3>array-like object</h3>
<pre><code class="prettyprint">
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
</code></pre>
</li>
</ul>
</section>
<section class="slide" id="functions-return">
<h2>Functions: Return</h2>
<ul>
<li><h3>Functions always return a value</h3></li>
<li><h3>If no return value is given <code>undefined</code> is returned</h3></li>
<li><h3>If invoked with <code>new</code> and no return is given the new object is returned</h3>
<pre><code class="prettyprint">var Car = function (speed) {
this.speed = speed;
};
var my_car = new Car('40 k/h');
</code></pre>
</li>
</ul>
</section>
<section class="slide" id="functions-scope">
<h2>Functions: Scope</h2>
<ul>
<li><h3>No block scope</h3></li>
<li><h3>Only function scope</h3>
<pre><code class="prettyprint">var foo = function () {
var a = 3, b = 5;
var bar = function () {
var b = 7, c = 11;
a += b + c;
};
bar();
};</code></pre>
</li>
</ul>
</section>
<section class="slide" id="functions-closure">
<h2>Functions: Closure</h2>
<ul>
<li><h3>Inner functions have access to outer function's parameters and variables.</h3>
<pre><code class="prettyprint">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</code></pre>
</li>
</ul>
</section>
<section class="slide" id="functions-module">
<h2>Functions: Module</h2>
<ul>
<li><h3>Can eliminate the use of global variables</h3>
<pre><code class="prettyprint">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</code></pre>
</li>
</ul>
</section>
<section class="slide" id="functions-memoization">
<h2>Functions: Memoization</h2>
<ul>
<li><h3>Remember the results of previous operations</h3>
<pre><code class="prettyprint">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</code></pre>
</li>
</ul>
</section>
<section class="slide" id="inheritance-pseudoclassical">
<h2>Inheritance: Pseudoclassical</h2>
<ul>
<li><h3>Intended to look sort of object-oriented</h3></li>
<li><h3>Provided by using <code>new</code> prefix</h3></li>
<li><h3>Hides the true nature of the language</h3>
<pre><code class="prettyprint">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</code></pre>
</li>
</ul>
</section>
<section class="slide" id="inheritance-prototypal">
<h2>Inheritance: Prototypal</h2>
<ul>
<li><h3>A new object can inherit the properties of an old object</h3></li>
<li><h3>Start with a useful object and then make many more like it</h3>
<pre><code class="prettyprint">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</code></pre>
</li>
</ul>
</section>
<section class="slide" id="inheritance-functional">
<h2>Inheritance: Functional</h2>
<ul>
<li><h3>Allows privacy</h3>
<pre><code class="prettyprint">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</code></pre>
</li>
</ul>
</section>
<section class="slide" id="Arrays">
<h2>Arrays</h2>
<ul>
<li><h3>Array-like objects</h3></li>
<li><h3>Linked to Array.prototype</h3></li>
<li><h3>No linear allocated memory or computed offest access</h3></li>
<li><h3>Have their own literal notation</h3></li>
<li><h3>Elements can be of any value</h3></li>
</ul>
</section>
<section class="slide" id="Arrays-2">
<h2>Arrays</h2>
<ul>
<li><h3>Array literal</h3>
<pre><code class="prettyprint">var a = [];
var misc = [ 'string', 98.6, true, null, undefined,
['nested', 'array'], {x: 1}, Infinity ];
</code></pre>
</li>
<li><h3>length property is not upper bound</h3>
<pre><code class="prettyprint">var a = [];
a.length // 0
a[10] = 1;
a.length // 11
a[4] // undefined</code></pre>
</li>
<li><h3>Have methods</h3>
<pre><code class="prettyprint">var a = [];
a.push(1);
a // [1] </code></pre>
</li>
</ul>
</section>
<section class="slide" id="bad">
<h2>Bad parts</h2>
<ul>
<li><h3>Global variables</h3></li>
<li><h3>No block scope</h3></li>
<li><h3>Semicolon insertion</h3>
<pre><code class="prettyprint">return
{
status: true
};
return {
status: true
};</code></pre>
</li>
</ul>
</section>
<section class="slide" id="bad-2">
<h2>Bad parts</h2>
<ul>
<li><h3>floating point</h3></li>
<li><h3>Phony arrays</h3></li>
<li><h3>+ overloading</h3>
<pre><code class="prettyprint">1 + 2 // 3
'1' + 2 // '12'
1 + '2' // '12'</code></pre>
</li>
<li><h3>typeof</h3>
<pre><code class="prettyprint">typeof null // object
typeof [] // object
</code></pre>
</li>
</ul>
</section>
<section class="slide" id="bad-3">
<h2>Bad parts</h2>
<ul>
<li><h3>eval</h3></li>
<li><h3>Bitwise operators</h3></li>
<li><h3>==</h3>
<pre><code class="prettyprint">'' == '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
</code></pre>
</li>
</ul>
</section>
<section class="slide" id="references">
<h2>References</h2>
<ul>
<li><h3>JavaScript: The Good Parts</h3><h4>by Douglas Crockford</h4></li>
</ul>
</section>
<section class="slide" id="thankyou">
<h1>Thank You</h1>
</section>
<script src="//ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.min.js"></script>
<!-- Deck Core and extensions -->
<!-- Initialize the deck -->
<script>
$(function() {
prettyPrint();
});
</script>
</div>
<br />
</div>mshalabyhttp://www.blogger.com/profile/13133192118777632030noreply@blogger.com0tag:blogger.com,1999:blog-7818676195859488270.post-44033447606222537382009-03-30T11:09:00.000-07:002009-05-11T12:42:23.183-07:00JavaScript Code Prettifier<style>pre.prettyprint{padding:2px;border:1px solid #888} .str { color:#181; font-style:italic } .kwd { color:#369; font-weight:bold } .com { color:#666 } .typ { color:#c40 } .lit { color:#900 } .pun { color:#000; font-weight:bold } .pln { color:#333 } .tag { color:#369; font-weight:bold } .atn { color:#939; font-weight:bold } .atv { color:#181 } .dec { color:#606 }</style><br /><br /><script> var loaded = false; var rawCodeArea; var codeHtmlArea; var preview; window.onload = function () { loaded = true ;}; var generateHtml = function () { rawCodeArea = document.getElementById('rawcode'); codeHtmlArea = document.getElementById('prettified'); preview = document.getElementById('preview'); htmlCode = document.getElementById('htmlCode'); codeHtml = prettyPrintOne(rawCodeArea.value); codeHtmlArea.value = codeHtml; preview.innerHTML = codeHtml; }; </script><br /><p><br />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 <a href="http://code.google.com/p/google-code-prettify/">google-code-prettify</a> project ( A Javascript module and CSS file that allows syntax highlighting of source code snippets in an html page ).<br /></p><br /><p><br />According to their <a href="http://google-code-prettify.googlecode.com/svn/trunk/README.html">README</a> file you should do the following to have it working:<br /></p><br /><ol><br /> <li><a href="http://google-code-prettify.googlecode.com/files/prettify-small-5-Jul-2008.zip">Download</a> a distribution<br /> </li><br /> <li>Include the script and stylesheets in your document<br /> (you will need to make sure the css and js file are on your server, and<br /> adjust the paths in the <tt>script</tt> and <tt>link</tt> tag)<br /> <pre class="prettyprint"><br /><span class="pun"><</span><span class="tag">link</span><span class="pln"> </span><span class="atn">href</span><span class="pun">=</span><span class="atv">"prettify.css"</span><span class="pln"> </span><span class="atn">type</span><span class="pun">=</span><span class="atv">"text/css"</span><span class="pln"> </span><span class="atn">rel</span><span class="pun">=</span><span class="atv">"stylesheet"</span><span class="pln"> </span><span class="pun">/></span><span class="pln"><br /></span><span class="pun"><</span><span class="tag">script</span><span class="pln"> </span><span class="atn">type</span><span class="pun">=</span><span class="atv">"text/javascript"</span><span class="pln"> </span><span class="atn">src</span><span class="pun">=</span><span class="atv">"prettify.js"</span><span class="pun">></</span><span class="tag">script</span><span class="pun">></span></pre><br /> </li><br /> <li>Add <code class="prettyprint"><span class="pln">onload</span><span class="pun">=</span><span class="str">"prettyPrint()"</span></code> to your<br /> document's body tag.<br /> </li><br /> <li>Modify the stylesheet to get the coloring you prefer</li><br /><li>Put code snippets in <code class="prettyprint"><tt><pre class="prettyprint">...</pre></tt> or <tt><code class="prettyprint">...</code></tt></code></li><br /></ol><br /><p><br /> <br /></p><br /><p><br />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 : <a href="/files/prettify_js.txt">http://intranet.espace.com.eg/files/prettify_js.txt</a> which I have uploaded earlier.<br /></p><br /><p><br />If that was not the case and all you've got is the HTML-format editor then you should try this way:<br /></p><br /><ol><br /> <li><a href="http://google-code-prettify.googlecode.com/files/prettify-small-8-Jan-2009.zip">Download</a> a small compressed version of the prettifier.</li><br /> <li>Copy the CSS text from prettify.css and paste it into a style element in your editor area.</li><br /> <li>Copy the JavaScript code from prettify.js into and paste it inside a script element.</li><br /> <li>Put code snippets in <code class="prettyprint"><tt><pre class="prettyprint">...</pre></tt> or <tt><code class="prettyprint">...</code></tt></code></li><br /> <li>put <code class="prettyprint">prettyPrint()</code> inside a script element at the end of your editor input</li><br /></ol><br /><p><br /> <br /></p><br /><h3>Need to see it in action?</h3><br /><p><br />You'll get to try it your self.<br /></p><br /><p><br />Type code in the text area to the left, press the prettify button and you'll see the magic.<br /></p><br /><h5 style="margin: 0pt; width: 49%; float: left">Type your code here:</h5><br /><h5 style="margin: 0pt; width: 49%; float: left">Syntax highlighted code:</h5><br /><div style="width: 49%; height: 200px; float: left"><br /><textarea id="rawcode" row="20" col="200" style="width: 100%; height: 100%"></textarea><br /></div><br /><div style="margin-left: 5px; margin-top: 3px; border: 1px solid ; overflow: auto; width: 49%; height: 200px; float: left"><br /><code id="preview"><br /></code><br /></div><br /><div style="clear: both"><br /><input value="prettify" onclick="generateHtml()" type="button" /><br /></div><br /><div><br /><h5 style="margin: 0pt">Generated HTML:</h5><br /><textarea id="prettified" row="20" col="200" style="width: 100%; height: 200px"></textarea><br /></div>mshalabyhttp://www.blogger.com/profile/13133192118777632030noreply@blogger.com0tag:blogger.com,1999:blog-7818676195859488270.post-90984761614092907142008-09-29T10:56:00.000-07:002009-05-11T11:24:49.643-07:00Javascript Multiple Inheritance<style type="text/css">pre.prettyprint{padding:2px;border:1px solid #888} .str { color:#181; font-style:italic } .kwd { color:#369; font-weight:bold } .com { color:#666 } .typ { color:#c40 } .lit { color:#900 } .pun { color:#000; font-weight:bold } .pln { color:#333 } .tag { color:#369; font-weight:bold } .atn { color:#939; font-weight:bold } .atv { color:#181 } .dec { color:#606 }</style><br /><!--script src="prettify_js.txt"></script--><br /><script src="http://www.gstatic.com/codesite/ph/14407163836014391775/js/prettify/prettify.js"></script><br /><p>Since <b>this</b> in the body of a function is the reference to the object used to call the function e.g. </p><br /><pre class="prettyprint"><br />obj.setProp = function(p) { this.prop = p }<br />obj.setProp(5)<br />obj.prop<br />=> 5<br /></pre><br /><p>and since Javascript constructor function is the same as any other javascript function and the only difference happens through the use of the <b>new</b> operator. We can use <b>this</b> (double meaning) to inject functionality provided by <b>multiple constructor functions</b> (sort of <b>multiple inheritance</b>) 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.</p><br /><pre class="prettyprint"><br />function Cat() { this.scratch = function () {alert("scratch!!")} }<br />function Dog() { this.bite = function () {alert("bite!!")} }<br />var catyDog = {}<br />catyDog.catify = Cat<br />catyDog.catify()<br />catyDog.dogify = Dog<br />catyDog.dogify()<br /></pre><br /><p>Now the <b>catyDog</b> object can both scratch and bite, so you better be careful.</p><br /><pre class="prettyprint"><br />catyDog.scratch()<br />// alerts "scratch!!"<br /><br />catyDog.bite()<br />// alerts "bite!!"<br /></pre><br /><p>Another way of doing the same thing but keeping the injecting functions kind of private:</p><br /><pre class="prettyprint"><br />function CatyDog()<br />{<br /> var me = this<br /> this.myownProp = 'special prop'<br /><br /> var init = function() {<br /> me.catify = Cat<br /> me.dogify = Dog<br /> me.catify()<br /> me.dogify()<br /> me.catify = undefined<br /> me.dogigy = undefined<br /> }<br /> init()<br />}<br /></pre><br /><p>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.</p><br /><p>In the previous example script if either <b>Cat</b> or <b>Dog</b> constructors had a prototype set, neither <b>catify</b> nor <b>dogify</b> will set the prototype for our object. Only the <b>new</b> operator would do such magic. So we will have to set the prototype of our choice ourselves using <b>__proto__</b> property or we can set the prototype for our constructor function and rely on the <b>new</b> operator magic.</p><br /><p>Now suppose that you need <b>CatyDog</b> to completely inherit <b>Dog</b> (including its prototype) while having <b>Cat</b> functionality.</p><br /><br /><pre class="prettyprint"><br />function CatyDog()<br />{<br /> var me = this<br /> this.myownProp = 'special prop'<br /> <br /> var init = function() {<br /> me.catify = Cat<br /> me.catify()<br /> me.catify = undefined<br /> }<br /> init()<br />}<br />CatyDog.prototype = new Dog<br /><br />var catyDog = new CatyDog<br /><br />catyDog.scratch()<br />catyDog.bite()<br /></pre><br /><p>The difference here is that any inherited <b>Dog</b> property including <b>bite</b> function will be fetched in the prototype each time it is used.<br /><br />Also here all <b>CatyDog</b> objects will have one single prototype <b>Dog</b> object.<br />So if you need every object to have its own prototype object can do it this way</p><br /><pre class="prettyprint"><br />function CatyDog()<br />{<br /> var me = this<br /> this.myownProp = 'special prop'<br /> <br /> var init = function() {<br /> me.catify = Cat<br /> me.catify()<br /> me.catify = undefined<br /> me.__proto__ = new Dog<br /> }<br /> init()<br />}<br /><br />var catyDog = new CatyDog<br /><br />catyDog.scratch()<br />catyDog.bite()<br /></pre><br /><script>prettyPrint()</script>mshalabyhttp://www.blogger.com/profile/13133192118777632030noreply@blogger.com0tag:blogger.com,1999:blog-7818676195859488270.post-11834870256889777202008-09-29T09:01:00.000-07:002009-05-11T10:54:24.311-07:00Easy Application Development for the iphone<style type="text/css">pre.prettyprint{padding:2px;border:1px solid #888} .str { color:#181; font-style:italic } .kwd { color:#369; font-weight:bold } .com { color:#666 } .typ { color:#c40 } .lit { color:#900 } .pun { color:#000; font-weight:bold } .pln { color:#333 } .tag { color:#369; font-weight:bold } .atn { color:#939; font-weight:bold } .atv { color:#181 } .dec { color:#606 } </style><br /><script src="http://www.gstatic.com/codesite/ph/14407163836014391775/js/prettify/prettify.js"></script><br /><script type="text/javascript">var detailed; var showDetailed = function() { if (!detailed) detailed = document.getElementById('detailed'); detailed.style.display = detailed.visible ? 'none' : 'block'; detailed.visible = !detailed.visible;};</script><br /><p>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.<br />But with <a href="http://www.jiggyapp.com/">Jiggy</a> 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.<br />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 <a href="http://www.jiggyapp.com/get_jiggy">here</a>)<br /><h4>What you have to do</h4><br /><p>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)<br />Now you can write, save and run your application form your browser ide.</p><br /><h4>What actually happens</h4><br /><p>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.<br />Jiggy Runtime is a collection of Jigglins ( Objective-C dynamic libraries that expose part of the Objective-C API to Javascript)<br />Jiggy Runtime can be extended by building new Jigglins that expose more of the native API.</p><br /><h4>An example</h4><br /><p>A Hello world marquee application.</p><br /><pre class="prettyprint"><br />// main.js<br />Plugins.load( "UIKit" );<br />include( "marquee.js" )<br />var window = new UIWindow( UIHardware.fullScreenApplicationContentRect );<br />window.setHidden( false );<br />window.orderFront();<br />window.makeKey();<br />window.backgroundColor = [ 1 , 1 , 1 , 1 ];<br />var mainView = new UIView();<br />window.setContentView( mainView );<br />var bounds = [0,0,window.bounds[2],20]<br />var delay = 4<br />var marquee = new Marquee( "Hello World", mainView, bounds, delay )<br />marquee.onStop = function() { marquee.start() }<br />marquee.start()<br /></pre><br /><p>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.<br />But the good news is I wrote it in Javascript.<br /><br />I made use of components already provided by the UIKit plugin namely UIScroller, UITextLabel, UIFrameAnimation and Animator.<br /><br />Here's the trick.<br /><br />A <code><span class="typ">UITextLabel</span></code> holds the text and using an animation it crosses the width of it's container view, a <code><span class="typ">UIScroller</span></code>.<br /><br />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.<br /><br />The delay passed to <code><span class="typ">UIFrameAnimator</span></code> should be the total time of the animation in seconds. <br /><br />So that delay for the <code><span class="typ">Marquee</span></code>, 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.<br />If you're interested here's the source.</p><br /><pre class="prettyprint"><br />// marquee.js<br />function Marquee(text, parent, bounds, delay, onStop) {<br /> var me = this<br /> var scroller = new UIScroller(bounds)<br /> var label = new UITextLabel([bounds[2], 0, bounds[2], bounds[3]])<br /> label.text = text<br /> scroller.addSubview(label)<br /> parent.addSubview(scroller)<br /> var startFrame = label.frame<br /> startFrame[2] = label.textSize[0]<br /> label.frame = startFrame<br /> this.delay = delay ? delay : 10<br /> this.onStop = onStop ? onStop : null<br /> var scroll<br /> var correctDelay = function(delay) {<br /> var w = scroller.bounds[2]<br /> return delay * (label.frame[2] + w) / w<br /> }<br /> this.start = function() {<br /> var endFrame = startFrame<br /> endFrame[0] = -endFrame[2]<br /> scroll = new UIFrameAnimation( label , 3, startFrame , endFrame )<br /> scroll.onStop = this.onStop<br /> Animator.addAnimation(scroll, correctDelay(me.delay), true)<br /> }<br />}<br /></pre><br /><p>If you're interested in a more complete Marquee constructor check <a onclick="showDetailed();return false">this</a> one out.</p><br /><pre id="detailed" class="prettyprint" style="display: none"><br />// marquee.js<br />function Marquee(text, parent, bounds, delay, onStop) {<br /> var ana = this<br /> var parentView = parent ? parent : null<br /> bounds = bounds ? bounds : [0, 0, window.bounds[2], 20]<br /> var scroller = new UIScroller(bounds)<br /> scroller.backgroundColor = [ 0 , 0 , 0 , 0 ];<br /> scroller.setScrollingEnabled(false)<br /> var label = new UITextLabel([bounds[2], 0, bounds[2], bounds[3]])<br /> label.backgroundColor = [ 0 , 0 , 0 , 0 ];<br /> var fontSize = bounds[3] * 0.75<br /> fontSize = fontSize > 76 ? 76 : fontSize<br /> label.setFont(new Font("Trebuchet MS", 0, fontSize))<br /> label.color = [ 1 , 1 , 1 , 1 ]<br /> label.centerHorizontally = true<br /> scroller.addSubview(label)<br /> if (parentView)<br /> parentView.addSubview(scroller)<br /> var startFrame = label.frame<br /> var curve = 3<br /> this.delay = delay ? delay : 10 <br /> this.onStop = onStop ? onStop : null <br /> var scroll<br /> var scrolling = false<br /> var updateSize = function() {<br /> startFrame[2] = label.textSize[0]<br /> label.frame = startFrame<br /> }<br /> this.setText = function(text)<br /> {<br /> label.text = text<br /> updateSize()<br /> }<br /> if (text)<br /> this.setText(text)<br /> var correctDelay = function(delay) {<br /> var w = scroller.bounds[2]<br /> return delay * (label.frame[2] + w) / w<br /> }<br /> this.start = function() {<br /> if (!scrolling) {<br /> var endFrame = startFrame<br /> endFrame[0] = -endFrame[2]<br /> scroll = new UIFrameAnimation( label ,<br /> curve , startFrame , endFrame )<br /> scroll.onStart = function() { <br /> scrolling = true<br /> }<br /> scroll.onStop = function() { <br /> scrolling = false<br /> label.frame = defaultFrame<br /> if (ana.onStop) <br /> ana.onStop()<br /> }<br /> Animator.addAnimation(scroll,<br /> correctDelay(ana.delay), true)<br /> }<br /> }<br /> this.stop = function() {<br /> if (scrolling)<br /> Animator.stopAnimation(scroll)<br /> }<br /> this.getLabel = function () { return label }<br /> this.setParentView = function(parent) {<br /> if (parent) {<br /> if (parentView)<br /> scroller.removeFromSuperview()<br /> parent.addSubview(scroller)<br /> parentView = parent<br /> }<br /> }<br /> this.setBackgroundColor = function(color) {<br /> scroller.backgroundColor = color<br /> }<br /> this.setColor = function(color) {<br /> label.color = color<br /> }<br /> this.setFont = function(font) {<br /> label.setFont(font)<br /> updateSize()<br /> }<br /> this.removeFromSuperview = function() {<br /> scroller.removeFromSuperview()<br /> }<br />}<br /></pre><br /><script>prettyPrint();</script>mshalabyhttp://www.blogger.com/profile/13133192118777632030noreply@blogger.com0tag:blogger.com,1999:blog-7818676195859488270.post-91151678842503909152007-07-17T03:11:00.000-07:002009-05-10T03:15:55.651-07:00Java vs. C++ - Part Two<div class="post-body entry-content"> <span style="font-family:trebuchet ms;">These are </span><strong style="font-family: trebuchet ms;">some more</strong><span style="font-family:trebuchet ms;"> differences between Java and C++.</span><div style="font-size: 100%; font-family: 'Trebuchet MS',Trebuchet,Verdana,Sans-Serif;"> <table style="border-style: inset; border-collapse: collapse;" border="3" cellpadding="10" width="100%"> <tbody> <tr><th style="width: 10%;"><br /></th><th style="width: 45%;">Java</th><th style="width: 45%;">C++</th></tr> <tr> <th>Class attributes and behaviors</th> <td>Attributes are "instance variables".<br />Behaviors are "methods"</td> <td>Attributes are "data members".<br />Behaviors are "member functions"</td> </tr> <tr> <th>Extending Class Object</th> <td>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 <span style="color: rgb(0, 0, 204);font-family:monospace;font-size:100%;" >extends</span> in its definition, it implicitly extends Object</td> <td>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.</td> </tr> <tr> <th>Packages</th> <td>Every class belongs to a package even if not explicitly specified it will be the default package ( the current directory )</td> <td>Classes do not have packages. Their containing header files are simply included in source files in which they are to be used</td> </tr> <tr> <th>Constructor name</th> <td>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.</td> <td>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.</td> </tr> <tr> <th>Initializing attributes</th> <td>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).</td> <td>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).</td> </tr> <tr> <th>Accessing hidden attributes</th> <td>An instance variable hidden by a local variable (having the same name) can be accessed in a method by:<pre style="font-family: monospace; font-size: 100%; color: rgb(0, 0, 204);">this.variableName</pre>(this is a reference to the current object)</td> <td>Such a hidden data member can be accessed in the member function by:<pre style="font-family: monospace; font-size: 100%; color: rgb(0, 0, 204);">ClassName::variableName<br />or<br />this->variableName</pre>(this here is a pointer to the current object)</td> </tr> <tr> <th>Access modifiers</th> <td>Each instance variable or method declaration in a Class definition must be preceded by an access modifier.</td> <td>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:<br />for classes: members are private by default.<br />for structs: members are public by default.</td> </tr> <tr> <th>Package access</th> <td>Members that have no access modifier preceding their declaration are accessible to all the classes included in the same package.</td> <td>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.</td> </tr> <tr> <th>Memory leaks</th> <td>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.</td> <td>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.</td> </tr> <tr> <th>Multiple inheritance</th> <td>Is not supported but interfaces are supported that allow a class to acquire multiple functionalities from any number of interfaces</td> <td>Is supported.</td> </tr> <tr> <th>Over-ridden superclass methods</th> <td>Can be accessed from the subclass by:<pre style="font-family: monospace; font-size: 100%; color: rgb(0, 0, 204);">super.methodName();</pre></td> <td>Such an over-ridden base-class member function can be accessed by the derived class by:<pre style="font-family: monospace; font-size: 100%; color: rgb(0, 0, 204);">BaseClassName::functionName();</pre></td> </tr> <tr> <th>Calling superclass constructor</th> <td>To explicitly call the superclass Parent constructor from the subclass Child constructor:<pre style="font-family: monospace; font-size: 100%; color: rgb(0, 0, 204);">public Child( int a, int b )<br />{<br />super( a );<br />x = b;<br />}<br /></pre>The calling statement must be the first statement in the subclass constructor</td> <td>To do the same thing here it goes like this:<pre style="font-family: monospace; font-size: 100%; color: rgb(0, 0, 204);">Child( int a, int b )<br />: Parent( a )<br />{<br />x = b;<br />}</pre>here we use the member initializer ( : ) to call the Parent constructor before the body of the constructor is executed</td> </tr> <tr> <th>Polymorphism and dynamic binding</th> <td>Applies automatically.<br />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.</td> <td>Does NOT apply automatically.<br />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.</td> </tr> <tr> <th><span style=";font-family:monospace;font-size:100%;" >final</span> methods and <span style=";font-family:monospace;font-size:100%;" >final</span> classes</th> <td><p>A method that is declared <span style="color: rgb(0, 0, 204);font-family:monospace;font-size:100%;" >final</span> cannot be overridden in a subclass.</p><p>A class that is declared <span style="color: rgb(0, 0, 204);font-family:monospace;font-size:100%;" >final</span> cannot be a superclass( cannot have subclasses).</p></td> <td>Does not have an equivalent in C++</td> </tr> <tr> <th><span style=";font-family:monospace;font-size:100%;" >const</span> functions</th> <td>Java has no equivalent for C++'s <span style="color: rgb(0, 0, 204);font-family:monospace;font-size:100%;" >const</span> functions</td> <td>A member function can be declared as <span style="color: rgb(0, 0, 204);font-family:monospace;font-size:100%;" >const</span>, indicating that calling that member function does not change the object.</td> </tr> <tr> <th>Abstract classes</th> <td>Are declared by using <span style="color: rgb(0, 0, 204);font-family:monospace;font-size:100%;" >abstract</span> and have one or more abstract mehtods<pre style="font-family: monospace; font-size: 100%; color: rgb(0, 0, 204);">public abstract ClassName {<br />private int instanceVariable;<br />public int someMethod1()....<br />public void someMethod2()...<br />public abstract int method(); <br />//abstract method<br />}</pre></td> <td>Must have one or more pure virtual functions <pre style="font-family: monospace; font-size: 100%; color: rgb(0, 0, 204);">class ClassName {<br />public:<br />virtual int someFunction1()...<br />virtual int someFunction2()...<br />virtual int function() = 0;<br />// pure virtual funtion<br />private:<br />int dataMember;<br />...<br />};</pre></td> </tr> <tr> <th>GUI support</th> <td>Normally has packages that support frames, windows, Graphical User Interface components.</td> <td>Does not normally support them. Appropriate third party libraries must be obtained to offer their support.</td> </tr> </tbody> </table> </div> </div> <span class="post-author vcard"> </span>mshalabyhttp://www.blogger.com/profile/13133192118777632030noreply@blogger.com0tag:blogger.com,1999:blog-7818676195859488270.post-2892546199940039952007-06-28T08:52:00.000-07:002012-05-15T02:16:13.319-07:00Java vs. C++ - Part One<h3 class="post-title entry-title"> <a href="http://mshalaby.blogspot.com/2009/04/java-vs.html">Java vs. C++ - Part One</a> </h3> These are <strong>only</strong> some of the differences between Java and C++ that I found so far that drew my attention and I think are worth mentioning. <table style="border-style: inset; border-collapse: collapse;" border="3" cellpadding="10" width="80%"><tbody><tr><th style="width: 10%;"><br /></th><th style="width: 45%;">Java</th><th style="width: 45%;">C++</th></tr> <tr><th>Compiling source code</th><td>When 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<br />( machine dependent ).</td><td>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.</td></tr> <tr><th>Function definitions </th><td>All function definitions and variable declarations are inside Classes even main(). Nothing is allowed to be outside a class except imports and package names.</td><td>Function definitions are outside class definitions. They have prototypes whose place decides function scope</td></tr> <tr><th>Including classes</th><td>Importing 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. </td><td>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.</td></tr> <tr><th>Ending class definitions</th><td>Class definitions end with } without a semicolon.</td><td>Class definitions end with };</td></tr> <tr><th>Creating objects</th><td>All objects must be created with <span style="color: rgb(0, 0, 204);font-family:monospace;font-size:100%;" >new</span>, so they are all dynamically allocated in the heap.<br />Only primitive data types can be allocated on the stack.</td><td>Objects can also be created and allocated without <span style="color: rgb(0, 0, 204);font-family:monospace;font-size:100%;" >new</span> so they are put on the stack in the scope of their declaration.</td></tr> <tr><th>Declaring a reference:</th><td>Declaring a reference to an object without using <span style="color: rgb(0, 0, 204);font-family:monospace;font-size:100%;" >new</span> to allocate the object only reserves space for the reference and no object is created in memory until <span style="color: rgb(0, 0, 204);font-family:monospace;font-size:100%;" >new</span> is used and the resulting object is given to the reference to point to it.</td><td>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.</td></tr> <tr><th>Calling static methods</th><td><span style="color: rgb(0, 0, 204);font-family:monospace;font-size:100%;" >ClassName.methodName( args.. );</span></td><td><span style="color: rgb(0, 0, 204);font-family:monospace;font-size:100%;" >ClassName::functionName( args.. );</span><br />or <span style="color: rgb(0, 0, 204);font-family:monospace;font-size:100%;" >ObjectName.functionName( args..);</span></td></tr> <tr><th>Wrapper classes</th><td>Java has wrapper classes for primitive data types that contains static methods for handling them<br />e.g.<span style="color: rgb(0, 0, 204);font-family:monospace;font-size:100%;" > String string = Integer.toString( intVariable );</span></td><td>C++ doesn't normally have them in its standard libraries</td></tr> <tr><th>Array declaration and memory allocation:</th><td>An array is considered an object that has to be allocated by new.<br /><pre style="font-family: monospace; font-size: 100%; color: rgb(0, 0, 204);"> int c[];<br /></pre> <p>declares the array reference</p> <pre style="font-family: monospace; font-size: 100%; color: rgb(0, 0, 204);"> c = new int[ 12 ];<br /></pre> <p>allocates the array and automatically initialize its elements to zero for numeric primitive types, false for boolean, null for references ( non-primitive types)<br />or</p> <pre style="font-family: monospace; font-size: 100%; color: rgb(0, 0, 204);"> int c[] = new int[ 12 ];<br />// in one step<br /></pre><p>you can never specify the number of elements in the [] in a declaration unlike C++.</p> <p>For multiple array declarations:</p> <pre style="font-family: monospace; font-size: 100%; color: rgb(0, 0, 204);"> double a[], b[]; <br /><br />a = new double[ 100 ];<br />b = new double[ 27 ];<br /><br />or<br /><br />double a[] = new double[ 100 ],<br />b[] = new double[ 27 ];<br />or<br />double[] a, b; <br /><br />a = new double[ 100 ];<br />b = new double[ 27 ];<br /><br />or<br /><br />double[] a = new double[ 100 ],<br />b = new double[ 27 ];<br /></pre> <p>Elements of an array of a primitive data type contain values of that data type.<br />While elements of an array of a non-primitive data type contian "references" to objects of that data type.<br /></p><p>( they have the value null by default )<br /></p> <p>Allocating and initializing arrays in declarations:</p> <pre style="font-family: monospace; font-size: 100%; color: rgb(0, 0, 204);"> int n[] = { 32, 27, 64, 18, 95,<br />14, 90, 70, 60, 37 };<br />// initializer list<br /></pre><p>Array size is determined by the number of elements in the list. Here <span style="color: rgb(0, 0, 204);font-family:monospace;font-size:100%;" >new</span> operator is provided by the compiler and the array object is also dynamically allocated.</p> <p>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: <strong>ArrayIndexOutOfBoundsException</strong>.</p></td><td><pre style="font-family: monospace; font-size: 100%; color: rgb(0, 0, 204);"> int c[ 12 ];<br /></pre><p>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.<br />For multiple array declaration:</p> <pre style="font-family: monospace; font-size: 100%; color: rgb(0, 0, 204);"> double a[ 100 ],<br />b[ 27 ];<br /></pre> <p>Elements of an array of any data type contain values or objects of that data type.<br />Objects for which an array can be declared must have a default constructor to be called for every element when the array is declared.</p><p>initializing arrays in declarations:</p> <pre style="font-family: monospace; font-size: 100%; color: rgb(0, 0, 204);"> int n[ 10 ] = { 0 };<br /></pre><p>initialize elements of array n to 0</p> <pre style="font-family: monospace; font-size: 100%; color: rgb(0, 0, 204);"> int n[] = { 1, 2, 3, 4, 5 };<br /></pre> <p>array size determined by the number of elements in the list </p> <p>No checking for array bounds is done by the compiler so the programmer must be very carful not to exceed the array length</p></td></tr> <tr><th>Multiple subscripted arrays</th><td><p>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.<br />i.e. arrays of arrays: </p> <pre style="font-family: monospace; font-size: 100%; color: rgb(0, 0, 204);"> int b[][] = { { 1, 2 },<br /> { 3, 4, 5 } };<br /></pre><p>b[ 0 ] is a reference to an array of 2 elements<br />b[ 1 ] is a reference to an array of 3 elements </p> <pre style="font-family: monospace; font-size: 100%; color: rgb(0, 0, 204);"> int b[][];<br />b = new int[ 3 ][ 3 ];<br /></pre> <p>3 by 3 array allocated</p> <pre style="font-family: monospace; font-size: 100%; color: rgb(0, 0, 204);"> int b[][];<br />b = new int[ 2 ][];<br /></pre><p>allocates rows</p> <pre style="font-family: monospace; font-size: 100%; color: rgb(0, 0, 204);"> b[ 0 ] = new int[ 5 ];<br /></pre><p> allocates columns for row 0 </p> <pre style="font-family: monospace; font-size: 100%; color: rgb(0, 0, 204);"> b[ 1 ] = new int[ 3 ];<br /></pre><p>allocates columns for row 1 </p></td><td><p>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. </p> <pre style="font-family: monospace; font-size: 100%; color: rgb(0, 0, 204);"> int b[][] = { { 1, 2 },<br /> { 3, 4, 5 } };<br /></pre><p>causes an error in C++ "error: declaration of 'b' as multidimensional array must have bounds for all dimensions except the first."<br /></p> <pre style="font-family: monospace; font-size: 100%; color: rgb(0, 0, 204);"> int b[][ 3 ] = { { 1, 2 },<br /> { 3, 4, 5 } };<br /></pre> <p>declares and preserves memory for a 2 by 3 multidimensional array b and initializes missing element in the list b[ 0 ][ 2 ] by 0. </p></td></tr> <tr><th>Passing arguments</th><td><p>Java does not allow the programmer to decide whether to pass an argument call-by-value or call-by-reference:<br />Primitive data type variables are always passed call-by-value.<br />Objects are not passed to methods; references to objects are passed<br />(call-by-value just like pointers in C++ are) so the method can manipulate the object directly.</p></td><td><p>You can pass primitive data types or objects either call-by-value or call-by-reference ( using pointers or references to them ).</p></td></tr> <tr><th>Returns</th><td><p>When returning information from a method via a return statement:</p> <p>Primitive data type variables are always returned by value (a copy is returned).<br />Objects are always returned by reference - a reference to the object is returned.</p></td><td><p>Objects and primitive data type variables can be returned by value or by reference</p></td></tr> <tr><th>Constant variables</th><td><p>Constant variables ( read only variables ) are declared using <span style="color: rgb(0, 0, 204);font-family:monospace;font-size:100%;" >final</span>. </p> </td><td><p>They are declared using <span style="color: rgb(0, 0, 204);font-family:monospace;font-size:100%;" >const</span>.</p></td></tr></tbody></table>mshalabyhttp://www.blogger.com/profile/13133192118777632030noreply@blogger.com0tag:blogger.com,1999:blog-7818676195859488270.post-28366636566711168802007-05-23T08:49:00.000-07:002012-05-15T02:04:01.437-07:00Virtual functions in C++<style>pre.prettyprint{padding:2px;border:1px solid #888} .str { color:#181; font-style:italic } .kwd { color:#369; font-weight:bold } .com { color:#666 } .typ { color:#c40 } .lit { color:#900 } .pun { color:#000; font-weight:bold } .pln { color:#333 } .tag { color:#369; font-weight:bold } .atn { color:#939; font-weight:bold } .atv { color:#181 } .dec { color:#606 }</style><br /><br /><script src="http://www.gstatic.com/codesite/ph/14407163836014391775/js/prettify/prettify.js"></script><span style=";font-family:times new roman;font-size:100%;" ><br /></span><blockquote style="font-family:times new roman;"><span style="font-size:100%;"> "In order to implement the concept of </span><span style="font-style: italic; font-weight: bold;font-size:100%;" >Polymorphism</span><span style="font-size:100%;"> which is a corner-stone of OOP the C++ compiler has to find a way to make it possible."</span></blockquote><span style=";font-family:times new roman;font-size:100%;" ><br /><br />Lets see how the story begins.<br /><br />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.<br /><br />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 </span> <span style="font-style: italic; font-weight: bold;font-family:times new roman;font-size:100%;" >settled</span><span style=";font-family:times new roman;font-size:100%;" > at compile time. ( </span><span style="font-weight: bold;font-family:times new roman;font-size:100%;" >static binding</span><span style=";font-family:times new roman;font-size:100%;" > )<br /><br />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.<br /><br />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.<br /><br />To solve this problem </span><span style="font-weight: bold; font-style: italic;font-family:times new roman;font-size:100%;" >Virtual functions</span><span style=";font-family:times new roman;font-size:100%;" > are used to allow </span><span style="font-style: italic; font-weight: bold;font-family:times new roman;font-size:100%;" >dynamic binding</span><span style=";font-family:times new roman;font-size:100%;" >.<br /><br /></span><blockquote style="font-family:times new roman;"><span style="font-size:100%;"> "...It seems that our friend, the compiler of course, is very resourceful."</span></blockquote><span style=";font-family:times new roman;font-size:100%;" ><br /><br />To support Polymorphism at runtime the compiler builds at compile time </span><span style="font-weight: bold; font-style: italic;font-family:times new roman;font-size:100%;" >virtual function tables</span><span style=";font-family:times new roman;font-size:100%;" > ( </span><span style="font-weight: bold;font-family:times new roman;font-size:100%;" >vtables</span><span style=";font-family:times new roman;font-size:100%;" > ). 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.<br /><br />The compiler then generates code that will:<br /><br />1. dereference the base class pointer to access the derived class object.<br />2. dereference its vtable pointer to access its class vtable.<br />3. add the appropriate offset to the vtable pointer to reach the desired function pointer.<br />4. dereference the function pointer to execute the appropriate function.<br /><br />This allows dynamic binding as the call to a virtual function will be </span><span style="font-style: italic;font-family:times new roman;font-size:100%;" >routed</span><span style=";font-family:times new roman;font-size:100%;" > at run time to the virtual function version appropriate for the class.<br /><br />Impressive isn't it?<br /><br />Well that made me try just for fun to write code that would do these steps instead of the compiler.<br /><br />But as I did this another question evolved.<br /><br /><span style="font-weight: bold;">How does member functions get their "this" pointer ?</span> ( pointer to the object the function is called for )<br /><br />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.<br /><br />I used in my example a single virtual function that takes no arguments and returns void.<br />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.<br /><br />So I tried calling the function and passing it the pointer to the object and it seemingly worked just fine.<br /><br />Here's the code I tried...<br /></span>
<pre style="padding: 5px; background: white none repeat scroll 0% 0%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial;color:blue;" class="prettyprint"><code style="font-size:85%;" >
#include <iostream>
using std::cout;
using std::endl;
class Parent {
public:
Parent( int = 0, int = 0 ); // default constructor
void setxy( int, int );
int getx() const { return x; }
int gety() const { return y; }
virtual void print();
private:
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()
{
Parent::print();
cout << " [ z: " << int =" 0," int =" 0," int =" 0," int =" 0," int =" 0);" e =" (">= 0 ? num : 0 );
}
void GrandChild::print()
{
Child::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;
}</code></pre><span style="font-size:85%;">The output should look like this:<br /><br /><pre style="padding: 20px; background: black none repeat scroll 0% 0%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; color: white;" width="75"><br />size of Parent = 12 bytes<br />size of Child = 20 bytes<br />size of GrandChild = 24 bytes<br /><br />The Derived objects accessed by an array of pointers to Parent:<br /><br />Object 1 : vtable ptr (0043FD90)<br /> pointer 1 in vtable is (00401480)<br /> ( pointer to virtual function 1 'print()' )<br /><br /> data: [ x: 7, y: 8]<br /><br />Object 2 : vtable ptr (0043FD80)<br /> pointer 1 in vtable is (004015B8)<br /> ( pointer to virtual function 1 'print()' )<br /><br /> data: [ x: 56, y: 23] [ z: 6, t: 12]<br /><br />Object 3 : vtable ptr (0043FD70)<br /> pointer 1 in vtable is (004016E6)<br /> ( pointer to virtual function 1 'print()' )<br /><br /> data: [ x: 4, y: 64] [ z: 34, t: 98] [ e: 39 ]<br /></pre><br /><br /><span style=";font-family:times new roman;font-size:100%;" ><span style="font-size:85%;"><br /></span>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.<br /><br />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 <span style="font-weight: bold; font-style: italic;">abstract classes</span> and they only used to provide an appropriate base class that passes a common interface and/or implementation to their derived classes.<br /><br />Abstract classes are not specific enough to define objects. <span style="font-style: italic; font-weight: bold;">Concrete classes</span> 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 <span style="font-style: italic; font-weight: bold;">pure virtual functions</span> which are those having = 0 added at the end of its function prototype.<br /><br /><pre class="prettyprint"><code style="font-size:85%;">virtual void draw() const = 0;</code></pre><br /><br />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.<br /><br />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.<br /><br />Another example could be class Furniture and it might look something like this:<br /><br /></span><pre style="padding: 5px; background: white none repeat scroll 0% 0%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial;color:blue;" class="prettyprint"><code style="font-size:85%;">Class Furniture {
public:
// ...
virtual double getVolume() const = 0; // a pure virtual
function
virtual void draw() const = 0; // another one here
// ...
}</code></pre><span style=";font-family:times new roman;font-size:100%;" ><br />Here class Furniture definition contains only the interface and implementation to be inherited.<br />It even does not contain any data members.<br /><br />That's it.<br />Hope you liked this article.<br /><br />I will be happy to receive your comments.</span></span>
<script>prettyPrint();</script>mshalabyhttp://www.blogger.com/profile/13133192118777632030noreply@blogger.com0