<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	xmlns:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>Seshhu&#039;s Blog</title>
	<atom:link href="http://techonhand.wordpress.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://techonhand.wordpress.com</link>
	<description>Just another WordPress.com weblog</description>
	<lastBuildDate>Sun, 11 Oct 2009 11:28:42 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain='techonhand.wordpress.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://0.gravatar.com/blavatar/eaae1950cec9e9897ab2b1812e98bc9e?s=96&#038;d=http%3A%2F%2Fs2.wp.com%2Fi%2Fbuttonw-com.png</url>
		<title>Seshhu&#039;s Blog</title>
		<link>http://techonhand.wordpress.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://techonhand.wordpress.com/osd.xml" title="Seshhu&#039;s Blog" />
	<atom:link rel='hub' href='http://techonhand.wordpress.com/?pushpress=hub'/>
		<item>
		<title>Exception Handling</title>
		<link>http://techonhand.wordpress.com/2009/10/11/exception-handling/</link>
		<comments>http://techonhand.wordpress.com/2009/10/11/exception-handling/#comments</comments>
		<pubDate>Sun, 11 Oct 2009 11:28:42 +0000</pubDate>
		<dc:creator>seshhu143</dc:creator>
				<category><![CDATA[C ++]]></category>

		<guid isPermaLink="false">http://techonhand.wordpress.com/?p=37</guid>
		<description><![CDATA[Learning Objectives At the end of this module, you will be able to Explain why do we need exception handling. Explain how to write C++ programs using exception handling. Explain how to declare and implement exception handing. Identify and list different exceptions. Apply exceptions for file handling, memory allocation and real world scenarios. Exception Handling [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=techonhand.wordpress.com&amp;blog=9884312&amp;post=37&amp;subd=techonhand&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<h2>Learning Objectives</h2>
<p>At the end of this module, you will be able to</p>
<ul>
<li>Explain why do we need exception handling.</li>
<li>Explain how to write C++ programs using exception handling.</li>
<li>Explain how to declare and implement exception handing.</li>
<li>Identify and list different exceptions.</li>
<li>Apply exceptions for file handling, memory allocation and real world scenarios.</li>
</ul>
<p><a id="Exception_Handling" name="Exception_Handling"></a></p>
<h2>Exception Handling</h2>
<p><a id="Introduction" name="Introduction"></a></p>
<h3>Introduction</h3>
<p>Exceptions are errors that occur at runtime. They are caused by a wide variety of exceptional circumstance, such as running out of memory, not being able to open a file, trying to initialize an object to an impossible value, or using an out-of-bounds index to a vector.</p>
<p><a id="Why_do_we_need_exceptions_.3F" name="Why_do_we_need_exceptions_.3F"></a></p>
<h3>Why do we need exceptions ?</h3>
<p>Why do we need a new mechanism to handle errors? Let’s look at how the process was handled in the past. C-language programs often signal an error by returning a particular value from the function in which it occurred. For example, disk-file functions often return NULL or 0 to signal an error. Each time you call one of these functions you check the return value:</p>
<p>&lt;source lang=&#8221;c&#8221;&gt; if( somefunc() == ERROR_RETURN_VALUE ) //handle the error or call error-handler function else //proceed normally if( anotherfunc() == NULL ) //handle the error or call error-handler function else //proceed normally if( thirdfunc() == 0 ) //handle the error or call error-handler function else //proceed normally &lt;/source&gt;</p>
<p>The Problem with this approach is that every single call to such a function must be examined by the program. Surrounding each function call with an if&#8230;else statement, and adding statements to handle the error (or call an error-handler routine), requires a lot of code and makes the listing convoluted and hard to read.</p>
<p><a id="Exception_Syntax" name="Exception_Syntax"></a></p>
<h3>Exception Syntax</h3>
<p>Imagine an application that creates and interacts with objects of a certain class. Ordinarily the application’s calls to the class member functions cause no problems. Sometimes, however, the application makes a mistake, causing an error to be detected in a member function. This member function then informs the application that an error has occurred. When exceptions are used, this is called throwing an exception. In the application we install a separate section of code to handle the error. This code is called an exception handler or catch block; it catches the exceptions thrown by the member function. Any code in the application that uses objects of the class is enclosed in a try block. Errors generated in the try block will be caught in the catch block. Code that doesn’t interact with the class need not be in a try block. Below image shows the arrangement.</p>
<p>The exception mechanism uses three new C++ keywords: throw, catch, and try. Also, we need to create a new kind of entity called an exception class. XSYNTAX is not a working program, but a skeleton program to show the syntax.</p>
<p>&lt;source lang=&#8221;cpp&#8221; start line=&#8221;1&#8243;&gt; // xsyntax.cpp // not a working program //////////////////////////////////////////////////////////////// class AClass //a class { public: 	class AnError //exception class 	{ 	};</p>
<p>void Func() //a member function 	{ 		if( /* error condition */ ) 		throw AnError(); //throw exception 	} };</p>
<p>////////////////////////////////////////////////////////////////</p>
<p>int main() //application { 	try //try block 	{ 		AClass obj1; //interact with AClass objects 		obj1.Func(); //may cause error 	} 	catch(AClass::AnError)  //exception handler 	{ 			//(catch block) 		//tell user about error, etc. 	} return 0; } &lt;/source&gt;</p>
<p>We start with a class called AClass, which represents any class in which errors might occur. An exception class, AnError, is specified in the public part of AClass. In AClass’s member functions we check for errors. If we find one, we throw an exception, using the keyword throw followed by the constructor for the error class:</p>
<p>&lt;source lang=&#8221;cpp&#8221;&gt; throw AnError(); //’throw’ followed by constructor for AnError class &lt;/source&gt;</p>
<p>In the main() part of the program we enclose any statements that interact with AClass in a try block. If any of these statements causes an error to be detected in an AClass member function, an exception will be thrown and control will go to the catch block that immediately follows the try block.</p>
<p><a id="A_simple_Exception_Example" name="A_simple_Exception_Example"></a></p>
<h3>A simple Exception Example</h3>
<p>Let’s look at a working program example that uses exceptions. This example creates a stack data structure in which integer data values could be stored. The application program might attempt to push too many objects onto the stack, thus exceeding the capacity of the array, or it might try to pop too many objects off the stack, thus obtaining invalid data. In the XSTAK program we use an exception to handle these two errors.</p>
<p>&lt;source lang=&#8221;cpp&#8221; start line=&#8221;1&#8243;&gt; // xstak.cpp // demonstrates exceptions</p>
<ol>
<li>include &lt;iostream&gt;</li>
</ol>
<p>using namespace std; const int MAX = 3; //stack holds 3 integers //////////////////////////////////////////////////////////////// class Stack { private: 	int st[MAX]; //array of integers</p>
<p>int top; //index of top of stack public: 	class Range //exception class for Stack 	{ //note: empty class body 	};</p>
<p>Stack() //constructor 	{ top = -1; }</p>
<p>void push(int var) 	{ 		if(top &gt;= MAX-1) //if stack full, 		throw Range(); //throw exception 		st[++top] = var; //put number on stack 	}</p>
<p>int pop() 	{ 		if(top &lt; 0) //if stack empty, 		throw Range(); //throw exception 		return st[top--]; //take number off stack 	} }; ////////////////////////////////////////////////////////////////</p>
<p>int main() { 	Stack s1; 	try 	{ 		s1.push(11); 		s1.push(22); 		s1.push(33); 		// s1.push(44); //oops: stack full 		cout &lt;&lt; “1: “ &lt;&lt; s1.pop() &lt;&lt; endl; 		cout &lt;&lt; “2: “ &lt;&lt; s1.pop() &lt;&lt; endl; 		cout &lt;&lt; “3: “ &lt;&lt; s1.pop() &lt;&lt; endl; 		cout &lt;&lt; “4: “ &lt;&lt; s1.pop() &lt;&lt; endl; //oops: stack empty 	} 	catch(Stack::Range) //exception handler 	{ 		cout &lt;&lt; “Exception: Stack Full or Empty” &lt;&lt; endl; 	} 		cout &lt;&lt; “Arrive here after catch (or normal exit)” &lt;&lt; endl; 	return 0; } &lt;/source&gt; Note that we’ve made the stack small so that it’s easier to trigger an exception by pushing too many items.</p>
<p>Let’s examine the features of this program that deal with exceptions. There are four of them. In the class specification there is an exception class. There are also statements that throw exceptions. In the main() part of the program there is a block of code that may cause exceptions (the try block), and a block of code that handles the exception (the catch block).</p>
<p><a id="Specifying_the_Exception_Class" name="Specifying_the_Exception_Class"></a></p>
<h4>Specifying the Exception Class</h4>
<p>The program first specifies an exception class within the Stack class: &lt;source lang=&#8221;cpp&#8221;&gt; class Range { //note: empty class body }; &lt;/source&gt;</p>
<p>Here the body of the class is empty, so objects of this class have no data and no member functions. All we really need in this simple example is the class name, Range. This name is used to connect a throw statement with a catch block. (The class body need not always be empty, as we’ll see later.)</p>
<p><a id="Throwing_an_Exception" name="Throwing_an_Exception"></a></p>
<h4>Throwing an Exception</h4>
<p>In the Stack class an exception occurs if the application tries to pop a value when the stack is empty or tries to push a value when the stack is full. To let the application know that it has made such a mistake when manipulating a Stack object, the member functions of the Stack class check for these conditions using if statements, and throw an exception if they occur. In XSTAK the exception is thrown in two places, both using the statement</p>
<p>&lt;source lang=&#8221;cpp&#8221;&gt; throw Range(); &lt;/source&gt;</p>
<p>The Range() part of this statement invokes the implicit constructor for the Range class, which creates an object of this class. The throw part of the statement transfers program control to the exception handler (which we’ll examine in a moment).</p>
<p><a id="The_try_Block" name="The_try_Block"></a></p>
<h4>The try Block</h4>
<p>All the statements in main() that might cause this exception—that is, statements that manipulate Stack objects—are enclosed in braces and preceded by the try keyword:</p>
<p>&lt;source lang=&#8221;cpp&#8221;&gt; try { //code that operates on objects that might cause an exception } &lt;/source&gt;</p>
<p>This is simply part of the application’s normal code; it’s what you would need to write even if you weren’t using exceptions. Not all the code in the program needs to be in a try block; just the code that interacts with the Stack class. Also, there can be many try blocks in your program, so you can access Stack objects from different places.</p>
<p><a id="The_Exception_Handler_.28Catch_Block.29" name="The_Exception_Handler_.28Catch_Block.29"></a></p>
<h4>The Exception Handler (Catch Block)</h4>
<p>The code that handles the exception is enclosed in braces, preceded by the catch keyword, with the exception class name in parentheses. The exception class name must include the class in which it is located. Here it’s</p>
<p>&lt;source lang=&#8221;cpp&#8221;&gt; Stack::Range. catch(Stack::Range) { //code that handles the exception } &lt;/source&gt;</p>
<p>This construction is called the exception handler. It must immediately follow the try block. In XSTAK the exception handler simply prints an error message to let the user know why the program failed.</p>
<p>Control “falls through” the bottom of the exception handler, so you can continue processing at that point. Or the exception handler may transfer control elsewhere, or (often) terminate the program.</p>
<p><a id="Sequence_of_Events" name="Sequence_of_Events"></a></p>
<h3>Sequence of Events</h3>
<p>Let’s summarize the sequence of events when an exception occurs:</p>
<ol>
<li>Code is executing normally outside a try block.</li>
<li>Control enters the try block.</li>
<li>A statement in the try block causes an error in a member function.</li>
<li>The member function throws an exception.</li>
<li>Control transfers to the exception handler (catch block) following the try block.</li>
</ol>
<p>That’s all there is to it. Notice how clean the resulting code is. Any of the statements in the try block could cause an exception, but we don’t need to worry about checking a return value for each one, because the try-throw-catch arrangement handles them all automatically. In this particular example we’ve deliberately created two statements that cause exceptions. The first</p>
<p>&lt;source lang=&#8221;cpp&#8221;&gt; s1.push(44); //pushes too many items  &lt;/source&gt;</p>
<p>causes an exception if you remove the comment symbol preceding it, and the second</p>
<p>&lt;source lang=&#8221;cpp&#8221;&gt; cout &lt;&lt; “4: “ &lt;&lt; s1.pop() &lt;&lt; endl; //pops item from empty stack &lt;/source&gt;</p>
<p>causes an exception if the first statement is commented out. Try it each way. In both cases the same error message will be displayed:</p>
<p>Stack Full or Empty</p>
<p><a id="Multiple_Exceptions" name="Multiple_Exceptions"></a></p>
<h3>Multiple Exceptions</h3>
<p>You can design a class to throw as many exceptions as you want. To show how this works, we’ll modify the XSTAK program to throw separate exceptions for attempting to push data on a full stack and attempting to pop data from an empty stack. Here’s the listing for XSTAK2:</p>
<p>&lt;source lang=&#8221;cpp&#8221; start line=&#8221;1&#8243;&gt; // xstak2.cpp // demonstrates two exception handlers</p>
<ol>
<li>include &lt;iostream&gt;</li>
</ol>
<p>using namespace std; const int MAX = 3; //stack holds 3 integers //////////////////////////////////////////////////////////////// class Stack { private: 	int st[MAX]; //stack: array of integers 	int top; //index of top of stack public: 	class Full { }; //exception class</p>
<p>class Empty { }; //exception class</p>
<p>//&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8211; 	Stack() //constructor 	{ top = -1; } //&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8211; 	void push(int var) //put number on stack 	{ 		if(top &gt;= MAX-1) //if stack full, 			throw Full(); //throw Full exception 		st[++top] = var; }</p>
<p>//&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8211; 	int pop() //take number off stack 	{ 		if(top &lt; 0) //if stack empty, 			throw Empty(); //throw Empty exception 	return st[top--]; 	} }; //////////////////////////////////////////////////////////////// int main() { 	Stack s1; 	try 	{ 		s1.push(11); 		s1.push(22); 		s1.push(33); 		// s1.push(44); //oops: stack full 		cout &lt;&lt; “1: “ &lt;&lt; s1.pop() &lt;&lt; endl; 		cout &lt;&lt; “2: “ &lt;&lt; s1.pop() &lt;&lt; endl; 		cout &lt;&lt; “3: “ &lt;&lt; s1.pop() &lt;&lt; endl; 		cout &lt;&lt; “4: “ &lt;&lt; s1.pop() &lt;&lt; endl; //oops: stack empty 	} 	catch(Stack::Full) 	{ 		cout &lt;&lt; “Exception: Stack Full” &lt;&lt; endl; 	} 	catch(Stack::Empty) 	{ 		cout &lt;&lt; “Exception: Stack Empty” &lt;&lt; endl; 	} 	return 0; } &lt;/source&gt;</p>
<p>In XSTAK2 we specify two exception classes:</p>
<p>&lt;source lang=&#8221;cpp&#8221;&gt; class Full { }; class Empty { }; The statement throw Full(); &lt;/source&gt;</p>
<p>is executed if the application calls push() when the stack is already full, and</p>
<p>&lt;source lang=&#8221;cpp&#8221;&gt; throw Empty(); &lt;/source&gt;</p>
<p>is executed if pop() is called when the stack is empty.</p>
<p>A separate catch block is used for each exception:</p>
<p>&lt;source lang=&#8221;cpp&#8221;&gt; try { //code that operates on Stack objects } catch(Stack::Full) { //code to handle Full exception } catch(Stack::Empty) { //code to handle Empty exception } &lt;/source&gt;</p>
<p>All the catch blocks used with a particular try block must immediately follow the try block. In this case each catch block simply prints a message: “Stack Full” or “Stack Empty”. Only one catch block is activated for a given exception. A group of catch blocks, or a catch ladder, operates a little like a switch statement, with only the appropriate section of code being executed. When an exception has been handled, control passes to the statement following all the catch blocks. (Unlike a switch statement, you don’t need to end each catch block with a break. In this way catch blocks act more like functions.)</p>
<p><a id="Specifing_Data_in_an_Exception_Class" name="Specifing_Data_in_an_Exception_Class"></a></p>
<h3>Specifing Data in an Exception Class</h3>
<p>What happens if the application needs more information about what caused an exception? For instance, in the XSTAK2 example, it might help the programmer to know what MAX elements the stack can have.</p>
<p>It’s convenient to make the data in an exception class public so it can be accessed directly by the exception handler. Here’s the specification for the new Full exception class in XSTAK2:</p>
<p>&lt;source lang=&#8221;cpp&#8221;&gt; class Full{ //exception class 	public: 		int maxElements; //Max elements the stack can store 		string message; //For name of the routine</p>
<p>Full(int max, string m){ maxElements = max; //put max in value in the object message = m; //put string in object } }; &lt;/source&gt; There are public variables for a string object, which will hold the name of the member function being called, and a type int, for the MAX stack elements.</p>
<p><a id="Initializing_an_Exception_Object" name="Initializing_an_Exception_Object"></a></p>
<h3>Initializing an Exception Object</h3>
<p>How do we initialize the data when we throw an exception? In the two-argument constructor for the Stack class we say</p>
<p>throw Full(MAX,&#8221;STACK PUSH &#8211;&gt; Stack is FULL&#8221;");</p>
<p>When the exception is thrown, the handler will display the string and MAX. The string will tell us which member function is throwing the exception, and the value of MAX. This additional data will make it easier for the programmer or user to figure out what caused the error.</p>
<p><a id="Resources" name="Resources"></a></p>
<h2>Resources</h2>
<p>Web Resources:</p>
<ul>
<li><a title="http://www.cplusplus.com/doc/tutorial/exceptions.html" rel="nofollow" href="http://www.cplusplus.com/doc/tutorial/exceptions.html">http://www.cplusplus.com/doc/tutorial/exceptions.html</a></li>
<li><a title="http://www.cprogramming.com/tutorial/exceptions.html" rel="nofollow" href="http://www.cprogramming.com/tutorial/exceptions.html">http://www.cprogramming.com/tutorial/exceptions.html</a></li>
</ul>
<p><a id="Steps_to_Attack_the_problem_sets" name="Steps_to_Attack_the_problem_sets"></a></p>
<h2>Steps to Attack the problem sets</h2>
<ul>
<li>Step 1: Read about Exception and try the example programs</li>
<li>Step 2: Go through the PPT on Exceptions and try stack program from the PPT.(you can copy paste the program)</li>
<li>Step 3: Go through the additional resources given.</li>
<li>Step 4: Attack the problem sets in the given order(Problem Set A and then Problem Set B &#8230;).</li>
<li>Step 5: If you are not clear with the problem sets then contact your respective mentor for clarification.</li>
</ul>
<p>Spend atleast 2 hours from step 1 to step 3</p>
<p><a id="Problem_Sets" name="Problem_Sets"></a></p>
<h2>Problem Sets</h2>
<p><a id="Problem_Set_A" name="Problem_Set_A"></a></p>
<h3>Problem Set A</h3>
<p><strong>1. </strong> Write an interactive program which divides two Integer Wrapper(Declaration is given) Class Objects. Overload divide(/) operator. Handle cases such as division-by-zero using exceptions. Write a test program to test the Wrapper Integer class for division.</p>
<p>The declaration of Integer class is</p>
<p>&lt;source lang=&#8221;cpp&#8221;&gt; class Integer{ 	private: 		int value; 	public: 		Integer(int v){value=v;};             //Consturctor 		int getInt();                       //returns the integer 		void setInt(int v);               //set the int value to the object 		Integer operator/= (const Integer &amp;);		 }; &lt;/source&gt;</p>
<pre>Name the program as: PA1_Integer.cpp
</pre>
<p><a id="Problem_Set_B" name="Problem_Set_B"></a></p>
<h3>Problem Set B</h3>
<p><strong>1. </strong>Add exceptions to the queue template you have written in Module 9. Throw two exceptions: one if the capacity of the queue is exceeded, the other if the program tries to remove an item from an empty queue. One way to handle this is to add a new data member to the queue: a count of the number of items currently in the queue. Increment the count when you insert an item, and decrement it when you remove an item. Throw an exception if this count exceeds the capacity of the queue, or if it becomes less than 0.</p>
<p>Add Exceptions in the Dynamic Array if the Memory allocation failed.</p>
<p>You might try making the main() part of this exercise interactive, so the user can put values on a queue and take them off. This makes it easier to exercise the queue. Following an exception, the program should allow the user to recover from a mistake without corrupting the contents of the queue.</p>
<pre>Name the DynamicArray program as: PB1_DynamicArray.cpp
Name the Queue program as: PB1_QueueException.cpp
Name the Header as: PB1_QueueException.h
</pre>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/techonhand.wordpress.com/37/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/techonhand.wordpress.com/37/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/techonhand.wordpress.com/37/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/techonhand.wordpress.com/37/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/techonhand.wordpress.com/37/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/techonhand.wordpress.com/37/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/techonhand.wordpress.com/37/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/techonhand.wordpress.com/37/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/techonhand.wordpress.com/37/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/techonhand.wordpress.com/37/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/techonhand.wordpress.com/37/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/techonhand.wordpress.com/37/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/techonhand.wordpress.com/37/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/techonhand.wordpress.com/37/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=techonhand.wordpress.com&amp;blog=9884312&amp;post=37&amp;subd=techonhand&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://techonhand.wordpress.com/2009/10/11/exception-handling/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/a93e36381d7b6e452b246a24496e3884?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">seshhu143</media:title>
		</media:content>
	</item>
		<item>
		<title>Templates</title>
		<link>http://techonhand.wordpress.com/2009/10/11/templates/</link>
		<comments>http://techonhand.wordpress.com/2009/10/11/templates/#comments</comments>
		<pubDate>Sun, 11 Oct 2009 11:26:23 +0000</pubDate>
		<dc:creator>seshhu143</dc:creator>
				<category><![CDATA[C ++]]></category>

		<guid isPermaLink="false">http://techonhand.wordpress.com/?p=35</guid>
		<description><![CDATA[Learning Objectives At the end of this Module, you will be able to: Explain how to achieve static polymorphic behavior through the use of templates Explain how to write generic code using templates Explain how to declare and implement function templates Explain how to declare and implement class templates Explain how to declare and implement [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=techonhand.wordpress.com&amp;blog=9884312&amp;post=35&amp;subd=techonhand&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<h2>Learning Objectives</h2>
<p>At the end of this Module, you will be able to:</p>
<ul>
<li>Explain how to achieve static polymorphic behavior through the use of templates</li>
<li>Explain how to write generic code using templates</li>
<li>Explain how to declare and implement function templates</li>
<li>Explain how to declare and implement class templates</li>
<li>Explain how to declare and implement class member function templates</li>
</ul>
<p><a id="Static_Polymorphism" name="Static_Polymorphism"></a></p>
<h2>Static Polymorphism</h2>
<p><a id="Introduction" name="Introduction"></a></p>
<h3>Introduction</h3>
<p>Static polymorphic behavior is realized at compile time. A class template acts as a generic class definition from which new class types can be defined by a simple change of parameter types. Whereas a normal class is used to create objects, a class template is used to define new class types, from which objects are then created. The compiler uses the types you supply, combined with the class template, to create a wholly new class type.</p>
<p>Understanding how to declare, implement, and use class and function templates will pay big dividends in many ways. Primarily, it provides you with a mechanism to write generic code. Learning to write generic code can potentially save you a lot of work.</p>
<p><a id="Definition_of_Template" name="Definition_of_Template"></a></p>
<h3>Definition of Template</h3>
<p>A template defines a related set of classes or functions. The related set of classes or functions defined by a template share the same code structure and functionality. The class or function template can then be used to declare a new class or function type.</p>
<p><strong>Function Templates</strong></p>
<p>A function template is a generic function declaration and definition from which different versions of the function can be created by the compiler based on the argument types used to call the function. If you think this sounds a lot like overloaded functions you are right. Function templates and overloaded functions are related as you will soon see.</p>
<p><strong>Class Templates</strong></p>
<p>A class template is a generic class declaration and definition from which different, but related, class types can be created by the compiler based on type parameters.</p>
<p><strong>Structure Templates</strong></p>
<p>A structure template is like a class template but using structures instead.</p>
<p><a id="How_Templates_Work:_An_Analogy" name="How_Templates_Work:_An_Analogy"></a></p>
<h3>How Templates Work: An Analogy</h3>
<p>When you declare and define a template you are creating a generic version of whatever piece of code you are writing, be it a function or a class. In the declaration and definition of the template you will use one or more identifiers as type placeholders. These type placeholders are similar in function to the placeholders in a form letter generated with a word processor.</p>
<p>The below figure illustrates a simple mail merge operation. A master letter is created with placeholders for certain data elements. The structure of the data source is mapped to the master letter by the placeholder identifiers name and age. When the mail merge function is executed, the data source is merged with the master letter to yield the finished letters. The master letter is a generic document that can be reused to generate many specific letter instances. Class and function templates work in similar fashion. A generic function or class is declared and defined. Placeholders are inserted into the code to reserve spots for actual data types. When specific versions of a template function are required the type substitutions are made based on the types of the arguments used to call the function. In the case of template classes, a special syntax is used when a new template class is declared.</p>
<p><a id="Declaring_And_Using_Function_Templates" name="Declaring_And_Using_Function_Templates"></a></p>
<h3>Declaring And Using Function Templates</h3>
<p>Up until now, if you wanted to create different versions of the same function to operate on different data types you would overload the function. For instance, if you wanted to declare a function named Sum() that took two arguments, added them together, and returned the result you could create several versions of the function like so:</p>
<p>&lt;source lang=&#8221;cpp&#8221;&gt; int Sum(int val1, int val2); float Sum(float val1, float val2); char Sum(char val1, char val2); &lt;/source&gt;</p>
<p>These three functions can be replaced with one function template.</p>
<p>&lt;source lang=&#8221;cpp&#8221; line start=&#8221;1&#8243; highlight=&#8221;4&#8243;&gt;</p>
<ol>
<li>ifndef SUM_TEMPLATE_H</li>
<li>define SUM_TEMPLATE_H</li>
</ol>
<p>template&lt;class T&gt; T Sum(T val1, T val2){</p>
<pre>return val1 + val2;
</pre>
<p>}</p>
<ol>
<li>endif</li>
</ol>
<p>&lt;/source&gt;</p>
<p>The Sum() function is declared to be a template by the keyword template appearing on line 4. Following the keyword template in angle brackets is the keyword class followed by a placeholder identifier named T. The class keyword as it is used here essentially means “any type”. The placeholder T will then appear somewhere in the function. It can appear in more than one place, as it does here in the parameter list. You can use any valid identifier as a placeholder name, not just T. You can also declare more than one placeholder.</p>
<p>To use the Sum() function template The Sum() function is called the same way as normal functions are called. The example below shows a main() function using the Sum() function on different data types.</p>
<p>&lt;source lang=&#8221;cpp&#8221; line start=&#8221;1&#8243; highlight=&#8221;5&#8243;&gt;</p>
<ol>
<li>include &lt;iostream&gt;</li>
<li>ifndef SUM_TEMPLATE_H</li>
<li>define SUM_TEMPLATE_H</li>
</ol>
<p>template&lt;class T&gt; T Sum(T val1, T val2){</p>
<pre>return val1 + val2;
</pre>
<p>}</p>
<ol>
<li>endif</li>
</ol>
<p>using namespace std; int main(){</p>
<pre>cout&lt;&lt;Sum(3, 25)&lt;&lt;endl;//Integer
cout&lt;&lt;Sum(3.456, 5.786)&lt;&lt;endl; //Float
cout&lt;&lt;Sum('a', 'b')&lt;&lt;endl; //Char
</pre>
<p>//cout&lt;&lt;Sum(3, 3.5)&lt;&lt;endl; return 0; } &lt;/source&gt;</p>
<p><a id="Using_Multiple_Placeholders" name="Using_Multiple_Placeholders"></a></p>
<h4>Using Multiple Placeholders</h4>
<p>The Sum() function template declared and defined in the above example used one type placeholder named T to reserve type spots in the function. Because both of the Sum() function’s parameters are reserved with the same placeholder they must be of the same type when the function is called. To illustrate, let us see what happens when the Sum() function is called with an integer and a float argument as shown in the following line of code:</p>
<p>cout&lt;&lt;Sum(3, 3.5)&lt;&lt;endl;</p>
<p>Error : in function int main() line no 15: no matching function for call to `Sum(int, double)</p>
<p>When the Sum() function template is called with two different argument types an error results. This error was produced using the Dev C++ 4.9.9.2. One way to eliminate this error is to declare the Sum() function template to use two different placeholders.</p>
<p>&lt;source lang=&#8221;cpp&#8221; line start=&#8221;1&#8243; highlight=&#8221;4&#8243;&gt;</p>
<ol>
<li>include &lt;iostream&gt;</li>
<li>ifndef SUM_TEMPLATE_H</li>
<li>define SUM_TEMPLATE_H</li>
</ol>
<p>template&lt;class T, class U&gt; T Sum(T val1, U val2){</p>
<pre> return val1 + val2;
}
</pre>
<ol>
<li>endif</li>
</ol>
<p>using namespace std; int main(){</p>
<pre>cout&lt;&lt;Sum(3, 25)&lt;&lt;endl;
cout&lt;&lt;Sum(3.456, 5.786)&lt;&lt;endl;
cout&lt;&lt;Sum('a', 'b')&lt;&lt;endl;
cout&lt;&lt;Sum(3, 3.5)&lt;&lt;endl;
return 0;
</pre>
<p>} &lt;/source&gt;</p>
<p>Notice now there are two type placeholders declared on line 5 of the above example. T and U. The U placeholder is used for the second parameter in the Sum() function while the T placeholder is used for the first parameter and the return value. This will solve one problem but introduce another. The above Example shows the revised Sum() function template in use.</p>
<p>Refer to line 14 of the above example. Notice now that the Sum() function is called with the first argument an integer and the second argument a float. By using two placeholders in the function template the error produced by using two different argument types is eliminated. However, the result type of the Sum() function is dictated by the first argument type. Since the T placeholder is used to reserve the type spot for both the first parameter and the return type of the function, whatever type the first argument to the function happens to be will also be the return type of the function. In this example it is an integer. So, the result of calling the Sum() function with the arguments 3 and 3.5 is 6, not 6.5! Notice what happens when the order of the arguments are swapped.<br />
To resolve the <strong>ambiguous</strong> return type issue simply declare yet another type place holder used specifically to dictate the function’s return type. The below example gives the revised Sum() function with the extra type placeholder V declared and used to reserve the return type.</p>
<p>&lt;source lang=&#8221;cpp&#8221; line start=&#8221;1&#8243; highlight=&#8221;4&#8243;&gt;</p>
<ol>
<li>include &lt;iostream&gt;</li>
<li>ifndef SUM_TEMPLATE_H</li>
<li>define SUM_TEMPLATE_H</li>
</ol>
<p>template&lt;class T, class U, class V&gt; V Sum(T val1, U val2){</p>
<pre>return val1 + val2;
</pre>
<p>}</p>
<ol>
<li>endif</li>
</ol>
<p>using namespace std; int main(){</p>
<pre>cout&lt;&lt;Sum&lt;int, int, int&gt;(3, 25)&lt;&lt;endl;
cout&lt;&lt;Sum&lt;double, double, double&gt;(3.456, 5.786)&lt;&lt;endl;
cout&lt;&lt;Sum&lt;char, char, char&gt;('a', 'b')&lt;&lt;endl;
cout&lt;&lt;Sum&lt;double, int, double&gt;(3.5, 3)&lt;&lt;endl;
</pre>
<p>return 0; } &lt;/source&gt;</p>
<p>Notice the Sum() function call on line 11. The function name Sum is followed by a series of type names enclosed in angle brackets. This is referred to as a template specialization. The order of type names appearing in the specialization map to the same order as the function template type parameters. On line 11 the Sum() function is being specialized to take two integers as arguments to the function and return an integer value. Following the specialization is the argument list appearing in parentheses as usual. Line 12 introduces another Sum() function specialization, as does line 13 and line 14. The specialization on line 14 says that the Sum() function will take a double as the first argument, an integer as the second argument, and return a double value.</p>
<p><a id="Declaring_And_Using_Class_Templates" name="Declaring_And_Using_Class_Templates"></a></p>
<h3>Declaring And Using Class Templates</h3>
<p>Class templates are used to declare and define a generic class structure. The compiler uses the class template and any types supplied via specialization to build a new class type. Let us begin the discussion of class templates with a simple Foo example. Example below shows the declaration and definition of a class template named Foo.</p>
<p>&lt;source lang=&#8221;cpp&#8221; line start=&#8221;1&#8243; highlight=&#8221;4&#8243;&gt;</p>
<ol>
<li>include &lt;iostream&gt;</li>
</ol>
<ol>
<li>ifndef FOOTEMPLATEDEF_H</li>
<li>define FOOTEMPLATEDEF_H</li>
</ol>
<p>template&lt;class T&gt; class Foo{ public: 	Foo(T _val); 	virtual ~Foo(); 	void setVal(T _val); 	T getVal(); private: 	T val; };</p>
<p>template&lt;class T&gt; Foo&lt;T&gt;::Foo(T _val):val(_val){}</p>
<p>template&lt;class T&gt; Foo&lt;T&gt;::~Foo(){}</p>
<p>template&lt;class T&gt; void Foo&lt;T&gt;::setVal(T _val){ 	val = _val; }</p>
<p>template&lt;class T&gt; T Foo&lt;T&gt;::getVal(){ 	return val; }</p>
<ol>
<li>endif</li>
</ol>
<p>using namespace std;</p>
<p>int main(){ 	Foo&lt;int&gt; f1(1); 	Foo&lt;char&gt; f2(&#8216;d&#8217;); 	cout&lt;&lt;f1.getVal()&lt;&lt;endl; 	cout&lt;&lt;f2.getVal()&lt;&lt;endl; 	return 0; } &lt;/source&gt;</p>
<p>The declaration of the Foo class templates begins on line 6 with the keyword template. There is only one template parameter declared named T. The T is used throughout the class declaration and definition to reserve a spot for the type declared when the Foo class is specialized.</p>
<p>Referring to line 33 of above example, notice how the Foo class template is specialized to use an int type. The important point to note in this example is that Foo&lt;int&gt; and Foo&lt;char&gt; are two distinct types.</p>
<p><a id="A_More_Complex_Class_Template_Example" name="A_More_Complex_Class_Template_Example"></a></p>
<h4>A More Complex Class Template Example</h4>
<p>The below Example gives the source code for a template of the DynamicArray class.</p>
<p>&lt;source lang=&#8221;cpp&#8221; line start=&#8221;1&#8243; highlight=&#8221;4&#8243;&gt;</p>
<ol>
<li>include &lt;iostream&gt;</li>
</ol>
<ol>
<li>ifndef _DYNAMIC_ARRAY_H</li>
<li>define _DYNAMIC_ARRAY_H</li>
</ol>
<p>template&lt;class T&gt; class DynamicArray{ public: 	DynamicArray(int _size = 5); 	virtual ~DynamicArray(); 	T&amp; operator[](unsigned i); 	int getSize(); private: 	T* its_array; 	int size; };</p>
<p>template&lt;class T&gt; DynamicArray&lt;T&gt;::DynamicArray(int _size):size(_size){ 	its_array = new T[_size]; 	for(int i=0; i&lt;size; i++) 		its_array[i] = static_cast&lt;T&gt;(0); }</p>
<p>template&lt;class T&gt; DynamicArray&lt;T&gt;::~DynamicArray(){ 	delete[] its_array; }</p>
<p>template&lt;class T&gt; T&amp; DynamicArray&lt;T&gt;::operator[](unsigned i){ if(i &gt;= (size)){ 	int newsize = size+10; 	T* temp = new T[size]; 	for(int j = 0; j&lt;size; j++){ 	temp[j] = its_array[j]; 	} 	delete[] its_array; 	its_array = new T[newsize]; 	for(int j = 0; j&lt;size; j++){ 		its_array[j] = temp[j]; 	} 	for(int j=size; j&lt;newsize; j++){ 		its_array[j] = static_cast&lt;T&gt;(0); 	} 	delete[] temp; 	size = newsize; 	return its_array[i]; }  else  	return its_array[i]; }</p>
<p>template&lt;class T&gt; int DynamicArray&lt;T&gt;::getSize(){ return size;}</p>
<ol>
<li>endif</li>
</ol>
<p>using namespace std;</p>
<p>int main(){ 	DynamicArray&lt;char&gt; d1; 	DynamicArray&lt;float&gt; d2; 	for(int i=0; i&lt;6; i++){ 		d1[i] = &#8216;a&#8217;; 	} 	for(int i=0; i&lt;6; i++){ 		d2[i] = (i + .5); 	} 	for(int i=0; i&lt;d1.getSize(); i++){ 		cout&lt;&lt;d1[i]&lt;&lt;&#8221; &#8220;&lt;&lt;d2[i]&lt;&lt;endl; 	} return 0; } &lt;/source&gt;</p>
<p>Converting the DynamicArray class into a class template increased its usefulness as it can now be used to hold different types of objects, even user-defined types. The above example gives a main() function showing the DynamicArray class template in use.</p>
<p><a id="Resources" name="Resources"></a></p>
<p><a id="Steps_to_attack_the_problem_sets" name="Steps_to_attack_the_problem_sets"></a></p>
<h2>Steps to attack the problem sets</h2>
<ul>
<li>Step 1: Read about <a title="CPP09:W1-M9" href="http://localhost/wiki/index.php/CPP09:W1-M9#Static_Polymorphism"> Static Polymorphism</a> and try sample programs(DynamicArray) given in Static Polymorphism(You can copy paste the programs)</li>
<li>Step 2: Go through the PPT on Templates and try stack program from the PPT.(you can copy paste the program)</li>
<li>Step 3: Go through the additional resources given.</li>
<li>Step 4: Attack the problem sets in the given order(Problem Set A and then Problem Set B &#8230;).</li>
<li>Step 5: If you are not clear with the problem sets then contact your respective mentor for clarification.</li>
</ul>
<p>Spend atleast 2 hours from Step 1 to Step 3.</p>
<p><a id="Problem_Sets" name="Problem_Sets"></a></p>
<h2>Problem Sets</h2>
<p><a id="Problem_Set_A" name="Problem_Set_A"></a></p>
<h3>Problem Set A</h3>
<p><strong>1. </strong>Create a function called swaps() that interchanges the values of the two arguments sent to it. (You will probably want to pass these arguments by reference.) Make the function into a template, so it can be used with all numerical data types (char, int, float, and so on). Write a main() program to exercise the function with several types.</p>
<pre>Name the program as: PA1_swaps.cpp
</pre>
<p><a id="Problem_Set_B" name="Problem_Set_B"></a></p>
<h3>Problem Set B</h3>
<p><strong>2. </strong>Create a function called amax() that returns the value of the largest element in an array. The arguments to the function should be the address of the array and its size. Make this function into a template so it will work with an array of any numerical type. Write a main() program that applies this function to arrays of various types.</p>
<pre>Name the program as:PB1_amax.cpp
</pre>
<p><a id="Problem_Set_C" name="Problem_Set_C"></a></p>
<h3>Problem Set C</h3>
<p><strong>3. </strong>A queue is a data-storage device. It’s like a stack, except that, instead of being last-in first-out, it’s first-in-first-out, like the line at a bank teller’s window. If you put in 1, 2, 3,you get back 1, 2, 3 in that order.</p>
<p>A stack needs only one index to an array (i.e top of the array). A queue, on the other hand, must keep track of two indexes to an array: one to the tail, where new items are added, and one to the head, where old items are removed. The tail follows the head through the array as items are added and removed. If either the tail or the head reaches the end of the array, it is reset to the beginning.</p>
<p>Write a class template for a queue class. Assume that the programmer using the queue won’t make any mistakes, like exceeding the capacity of the queue or trying to remove an item when the queue is empty. Define several queues of different data types and insert and remove data from them.</p>
<p>Use the <a title="CPP09:W1-M9" href="http://localhost/wiki/index.php/CPP09:W1-M9#A_More_Complex_Class_Template_Example"> dynamicarray</a> discussed previously for implementing the queue.</p>
<p>Write the declaration and defining of Queue template in separate header file and a Test program to test the queue in separate source file.</p>
<p>Refer:</p>
<ul>
<li><a title="http://www.angelfire.com/ma/masterscript/queues.html" rel="nofollow" href="http://www.angelfire.com/ma/masterscript/queues.html">Queue Animation  Java Applet(Animation) represents a simple queue at a shop</a></li>
</ul>
<pre>Name the Header files as: PC1_queue.h
Name the Test program as: PC1_queueTest.cpp
</pre>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/techonhand.wordpress.com/35/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/techonhand.wordpress.com/35/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/techonhand.wordpress.com/35/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/techonhand.wordpress.com/35/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/techonhand.wordpress.com/35/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/techonhand.wordpress.com/35/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/techonhand.wordpress.com/35/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/techonhand.wordpress.com/35/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/techonhand.wordpress.com/35/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/techonhand.wordpress.com/35/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/techonhand.wordpress.com/35/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/techonhand.wordpress.com/35/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/techonhand.wordpress.com/35/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/techonhand.wordpress.com/35/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=techonhand.wordpress.com&amp;blog=9884312&amp;post=35&amp;subd=techonhand&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://techonhand.wordpress.com/2009/10/11/templates/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/a93e36381d7b6e452b246a24496e3884?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">seshhu143</media:title>
		</media:content>
	</item>
		<item>
		<title>Friend Functions</title>
		<link>http://techonhand.wordpress.com/2009/10/11/friend-functions/</link>
		<comments>http://techonhand.wordpress.com/2009/10/11/friend-functions/#comments</comments>
		<pubDate>Sun, 11 Oct 2009 11:23:19 +0000</pubDate>
		<dc:creator>seshhu143</dc:creator>
				<category><![CDATA[C ++]]></category>

		<guid isPermaLink="false">http://techonhand.wordpress.com/?p=33</guid>
		<description><![CDATA[Learning Objectives At the end of this module, you will able to: Explain and use friend functions in C++ programs Implement software objects as friends to one another Introduction Friend The concepts of encapsulation and data hiding dictate that nonmember functions should not be able to access an object’s private or protected data. The policy [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=techonhand.wordpress.com&amp;blog=9884312&amp;post=33&amp;subd=techonhand&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<h2>Learning Objectives</h2>
<p>At the end of this module, you will able to:</p>
<ul>
<li>Explain and use friend functions in C++ programs</li>
<li>Implement software objects as friends to one another</li>
</ul>
<h2>Introduction</h2>
<h3>Friend</h3>
<p>The concepts of encapsulation and data hiding dictate that nonmember functions should not be able to access an object’s private or protected data. The policy is, if you’re not a member, you can’t get in. However, there are situations where such rigid discrimination leads to considerable inconvenience. in order to access the non-public members of a class, C++ provides the <strong>friend</strong> facility.</p>
<p><strong>Friend Functions</strong></p>
<p>Imagine that you want a function to operate on objects of two different classes. Perhaps the function will take objects of the two classes as arguments, and operate on their private data. In this situation there’s nothing like a friend function. Here’s a simple example, FRIEND, that shows how friend functions can act as a bridge between two classes:</p>
<p>&lt;source lang=&#8221;cpp&#8221;&gt; // friend.cpp // friend functions</p>
<ol>
<li>include &lt;iostream&gt;</li>
</ol>
<p>using namespace std; //////////////////////////////////////////////////////////////// class beta; //needed for frifunc declaration class alpha { private: 	int data; public: 	alpha() : data(3) { } //no-arg constructor 	friend int frifunc(alpha, beta); //friend function }; //////////////////////////////////////////////////////////////// class beta { private: 	int data; public: 	beta() : data(7) { } //no-arg constructor 	friend int frifunc(alpha, beta); //friend function }; //////////////////////////////////////////////////////////////// int frifunc(alpha a, beta b) //function definition { 	return( a.data + b.data ); } //&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8211; int main() {</p>
<pre>alpha aa;
beta bb;
cout &lt;&lt; frifunc(aa, bb) &lt;&lt; endl; //call the function
return 0;
</pre>
<p>} &lt;/source&gt;</p>
<p>In this program, the two classes are alpha and beta. The constructors in these classes initialize their single data items to fixed values (3 in alpha and 7 in beta).</p>
<p>We want the function frifunc() to have access to both of these private data members, so we make it a friend function. It’s declared with the friend keyword in both classes:</p>
<p>friend int frifunc(alpha, beta);</p>
<p>This declaration can be placed anywhere in the class; it doesn’t matter whether it goes in the public or the private section.</p>
<p>An object of each class is passed as an argument to the function frifunc(), and it accesses the private data member of both classes through these arguments. The function doesn’t do much: It adds the data items and returns the sum. The main() program calls this function and prints the result.</p>
<p>A minor point: Remember that a class can’t be referred to until it has been declared. Class beta is referred to in the declaration of the function frifunc() in class alpha, so beta must be declared before alpha. Hence the declaration class beta; at the beginning of the program.</p>
<h3>Friend Classes</h3>
<p>The member functions of a class can all be made friends at the same time when you make the entire class a friend. The program FRICLASS shows how this looks.</p>
<p>&lt;source lang=&#8221;cpp&#8221;&gt; // friclass.cpp // friend classes</p>
<ol>
<li>include &lt;iostream&gt;</li>
</ol>
<p>using namespace std; //////////////////////////////////////////////////////////////// class alpha { private: 	int data1; public: 	alpha() : data1(99) { } //constructor 	friend class beta; //beta is a friend class }; //////////////////////////////////////////////////////////////// class beta { //all member functions can public: //access private alpha data 	void func1(alpha a) { cout &lt;&lt; “\ndata1=” &lt;&lt; a.data1; } 	void func2(alpha a) { cout &lt;&lt; “\ndata1=” &lt;&lt; a.data1; } }; //////////////////////////////////////////////////////////////// int main() {</p>
<pre> alpha a;
 beta b;
 b.func1(a);
 b.func2(a);
 cout &lt;&lt; endl;
 return 0;
</pre>
<p>} &lt;/source&gt;</p>
<p>In class alpha the entire class beta is proclaimed a friend. Now all the member functions of beta can access the private data of alpha (in this program, the single data item data1). Note that in the friend declaration we specify that beta is a class using the class keyword:</p>
<p>friend class beta;</p>
<p>We could have also declared beta to be a class before the alpha class specifier, as in previous examples</p>
<p>class beta;</p>
<p>and then, within alpha, referred to beta without the class keyword:</p>
<p>friend beta;</p>
<h2>Resources</h2>
<ul>
<li>Refer previous modules on how to Identify a class, it&#8217;s state and behavior.</li>
</ul>
<ul>
<li><a title="http://xoax.net/comp/cpp/console/Lesson9.php" rel="nofollow" href="http://xoax.net/comp/cpp/console/Lesson9.php">Lesson 9: Tic Tac Toe Supporting Material</a></li>
</ul>
<h2>Steps to solve the problems sets</h2>
<ul>
<li>Read the introduction part of this module</li>
<li>View the video and read the supporting material</li>
<li>Think about how to write the tic tac toe program with objects.</li>
</ul>
<p>Spend atleast 1 hour on the resources and Other modules covered so far.</p>
<h2>Problem Sets</h2>
<h3>Problem Set A</h3>
<p><strong>1. </strong>Game Program: The object of tic-tac-toe is to get three X’s or three O’s in a row either horizontally, vertically or diagonally. The tic-tac-toe game board is a 3 x 3 grid and looks something like this:</p>
<p>During a typical game, players takes turns placing their X’s and O’s on the game board. The first to get their pattern in a row wins. The follow game board represents what the results of a typical game might look like:</p>
<p>Use a 3 x 3 array of cell objects to track player turns. Check the array after each player’s turn to see if they’ve won. Draw the game board on the screen after each turn so players can see the game’s progress. Make it a two player game.</p>
<p>Use Object Oriented Programming approach to solve this problem, thought the problem can be solved simple as presented in the video given.</p>
<p>Write a game program called tic-tac-toe by Identifying the Game as a class consists of Player Objects and Board Object. Board consists of Cell Objects representing the cell in the board.</p>
<p>Identify the Objects in the game with attributes and behavior.</p>
<p>Player can have player Name as an attribute and behavior as playing the game.</p>
<p>Identify and the write friend functions\classes in the board class, cell class, player class and Game class.</p>
<p>Use your imagination to identify the objects, It&#8217;s not limited to the classes which we have defined.</p>
<pre>Name the program as:- PA1_TicTacToe.cpp
</pre>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/techonhand.wordpress.com/33/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/techonhand.wordpress.com/33/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/techonhand.wordpress.com/33/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/techonhand.wordpress.com/33/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/techonhand.wordpress.com/33/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/techonhand.wordpress.com/33/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/techonhand.wordpress.com/33/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/techonhand.wordpress.com/33/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/techonhand.wordpress.com/33/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/techonhand.wordpress.com/33/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/techonhand.wordpress.com/33/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/techonhand.wordpress.com/33/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/techonhand.wordpress.com/33/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/techonhand.wordpress.com/33/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=techonhand.wordpress.com&amp;blog=9884312&amp;post=33&amp;subd=techonhand&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://techonhand.wordpress.com/2009/10/11/friend-functions/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/a93e36381d7b6e452b246a24496e3884?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">seshhu143</media:title>
		</media:content>
	</item>
		<item>
		<title>Polymorphism</title>
		<link>http://techonhand.wordpress.com/2009/10/11/polymorphism/</link>
		<comments>http://techonhand.wordpress.com/2009/10/11/polymorphism/#comments</comments>
		<pubDate>Sun, 11 Oct 2009 11:20:17 +0000</pubDate>
		<dc:creator>seshhu143</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://techonhand.wordpress.com/?p=31</guid>
		<description><![CDATA[Introduction Polymorphism Polymorphism is the ability to associate more than one implementation with the same operation. The binding of the operation with the implementation, can be decided at compile time or at run time. In object orientation, polymorphism can exist in two ways. Hierarchy independent &#8211; This takes the form of overloading, where the same [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=techonhand.wordpress.com&amp;blog=9884312&amp;post=31&amp;subd=techonhand&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<h2>Introduction</h2>
<p><a id="Polymorphism" name="Polymorphism"></a></p>
<h3>Polymorphism</h3>
<p>Polymorphism is the ability to associate more than one implementation with the same operation. The binding of the operation with the implementation, can be decided at compile time or at run time. In object orientation, polymorphism can exist in two ways.</p>
<ul>
<li><strong>Hierarchy independent</strong> &#8211; This takes the form of overloading, where the same name of an operation, has different implementations in different classes and these classes need not be related by class hierarchy.</li>
<li><strong>Hierarchy dependent</strong>- Here, an operation defined in the superclass can have any number of implementations along the class hierarchy. This type of polymorphism is referred to as universal polymorphism or overriding. The operation can be bound to any of the implementations. This resolution can take place, at compile time or at run time.</li>
</ul>
<p><a id="Pointers" name="Pointers"></a></p>
<h3>Pointers</h3>
<p><a id="Address_and_Pointers" name="Address_and_Pointers"></a></p>
<h4>Address and Pointers</h4>
<p>The ideas behind pointers are not complicated. Here’s the first key concept: Every byte in the computer’s memory has an address. Addresses are numbers, just as they are for houses on a street. The numbers start at 0 and go up from there—1, 2, 3, and so on. If you have 1MB of memory, the highest address is 1,048,575. (Of course you have much more.)</p>
<p>Your program, when it is loaded into memory, occupies a certain range of these addresses. That means that every <strong>variable</strong> and every <strong>function</strong> in your program starts at a particular address.</p>
<p><a id="Pointers_to_void" name="Pointers_to_void"></a></p>
<h4>Pointers to void</h4>
<p>Before we go on to see pointers at work, we should note one peculiarity of pointer data types.Ordinarily, the address that you put in a pointer must be the same type as the pointer. You can’t assign the address of a float variable to a pointer to int, for example:</p>
<div style="text-align:left;" dir="ltr">
<div>
<pre>float flovar = 98.6;
int* ptrint = &amp;flovar; //ERROR: can’t assign float* to int*</pre>
</div>
</div>
<p>However, there is an exception to this. There is a sort of general-purpose pointer that can point to any data type. This is called a pointer to void, and is defined like this:</p>
<div style="text-align:left;" dir="ltr">
<div>
<pre>void* ptr; //ptr can point to any data type</pre>
</div>
</div>
<p>Such pointers have certain specialized uses, such as passing pointers to functions that operate independently of the data type pointed to.</p>
<p>The next example uses a pointer to void and also shows that, if you don’t use void, you must be careful to assign pointers an address of the same type as the pointer. Here’s the listing for PTRVOID:</p>
<div style="text-align:left;" dir="ltr">
<div>
<pre>// ptrvoid.cpp
// pointers to type void
#include
using namespace std;
int main()
{
int intvar; //integer variable
float flovar; //float variable
int* ptrint; //define pointer to int
float* ptrflo; //define pointer to float
void* ptrvoid; //define pointer to void
ptrint = &amp;intvar; //ok, int* to int*
// ptrint = &amp;flovar; //error, float* to int*
// ptrflo = &amp;intvar; //error, int* to float*
ptrflo = &amp;flovar; //ok, float* to float*
ptrvoid = &amp;intvar; //ok, int* to void*
ptrvoid = &amp;flovar; //ok, float* to void*
return 0;
}</pre>
</div>
</div>
<p>You can assign the address of intvar to ptrint because they are both type int*, but you can’t assign the address of flovar to ptrint because the first is type float* and the second is type int*. However, ptrvoid can be given any pointer value, such as int*, because it is a pointer to void.</p>
<p>If for some unusual reason you really need to assign one kind of pointer type to another, you can use the reinterpret_cast. For the lines commented out in PTRVOID, that would look like this:</p>
<div style="text-align:left;" dir="ltr">
<div>
<pre>ptrint = reinterpret_cast&lt;int*&gt;(flovar);
ptrflo = reinterpret_cast&lt;float*&gt;(intvar);</pre>
</div>
</div>
<p>The use of reinterpret_cast in this way is not recommended, but occasionally it’s the only way out of a difficult situation. Static casts won’t work with pointers. Old-style C casts can be used, but are always a bad idea in C++.</p>
<p><a id="Base_class_Pointers" name="Base_class_Pointers"></a></p>
<h4>Base class Pointers</h4>
<p>In C++ a pointer of a base class can point to an object of any of its derived class.</p>
<p>In the example given below shows what happens when a base class and derived classes all have functions with the same name, and you access these functions using pointers. Here is the listing of BASEPOINT</p>
<div style="text-align:left;" dir="ltr">
<div>
<pre>// basepoint.cpp
// normal functions accessed from pointer
#include
using namespace std;
////////////////////////////////////////////////////////////////
class Base //base class
{
public:
      void show(){ cout &lt;&lt; "Base\n"; }
};
////////////////////////////////////////////////////////////////
class Derv1 : public Base //derived class 1
{
public:
      void show()
        { cout &lt;&lt; "Derv1\n"; }
};
////////////////////////////////////////////////////////////////
class Derv2 : public Base //derived class 2
{
public:
      void show()
           { cout &lt;&lt; "Derv2\n"; }
};
////////////////////////////////////////////////////////////////
int main()
{
Derv1 dv1; //object of derived class 1
Derv2 dv2; //object of derived class 2

Base* ptr; //pointer to base class

Derv1 *pdv1; //pointer to Derv1
Derv2 *pdv2; //pointer to Derv2

ptr = &amp;dv1; //put address of dv1 in pointer
ptr-&gt;show(); //execute show()

ptr = &amp;dv2; //put address of dv2 in pointer
ptr-&gt;show(); //execute show()

ptr = &amp;dv1; //put address of dv1 in pointer
if(reinterpret_cast&lt;Derv1 *&gt;(ptr) !=0){
  pdv1 =  reinterpret_cast&lt;Derv1 *&gt;(ptr);
  pdv1-&gt;show();
}
ptr = &amp;dv2; //put address of dv2 in pointer
if(reinterpret_cast&lt;Derv2 *&gt;(ptr) !=0){
  pdv2 =  reinterpret_cast&lt;Derv2 *&gt;(ptr);
  pdv2-&gt;show();
}
return 0;
}</pre>
</div>
</div>
<p>The <em>Derv1</em> and <em>Derv2</em> classes are derived from class Base. Each of these three classes has a member function show(). In main() we create objects of class Derv1 and Derv2, and a pointer to class Base. Then we put the address of a derived class object in the base class pointer in the line</p>
<div style="text-align:left;" dir="ltr">
<div>
<pre>ptr = &amp;dv1; // derived class address in base class pointer</pre>
</div>
</div>
<p>But wait—how can we get away with this? Doesn’t the compiler complain that we’re assigning an address of one type (Derv1) to a pointer of another (Base)? On the contrary, the compiler is perfectly happy, because type checking has been relaxed in this situation, for reasons that will become apparent soon. The rule is that pointers to objects of a derived class are type-compatible with pointers to objects of the base class.</p>
<p>Now the question is, when you execute the line</p>
<div style="text-align:left;" dir="ltr">
<div>
<pre>ptr-&gt;show();</pre>
</div>
</div>
<p>what function is called? Is it Base::show() or Derv1::show()? Again, in the last two lines of BASEPOINT we put the address of an object of class Derv2 in the pointer, and again execute</p>
<div style="text-align:left;" dir="ltr">
<div>
<pre>ptr-&gt;show();</pre>
</div>
</div>
<p>Which of the show() functions is called here? The output from the program answers these questions:</p>
<p>Base</p>
<p>Base</p>
<p>As you can see, the function in the base class is always executed. The compiler ignores the contents of the pointer ptr and chooses the member function that matches the type of the pointer, as shown in Figure below.</p>
<p><img src="http://wiki.msitprogram.net/CPP09/W1/M7/pointeraccess.jpg" alt="pointeraccess.jpg" /></p>
<p>Sometimes this is what we want, but it doesn’t solve the problem posed at the beginning of this section: accessing objects of different classes using the same statement.</p>
<p>You can use reinterpret_cast to cast the pointer of it&#8217;s type and use it. But that doesn&#8217;t solve the problem if u have hundreds of derived class from the base class.</p>
<p><a id="Virtual_Functions" name="Virtual_Functions"></a></p>
<h3>Virtual Functions</h3>
<p>Virtual means <em>existing in appearance but not in reality</em>. When virtual functions are used, a program that appears to be calling a function of one class may in reality be calling a function of a different class. Why are virtual functions needed? Suppose you have a number of objects of different classes but you want to put them all in an array and perform a particular operation on them using the same function call. For example, suppose a geometry program includes several different shapes: a triangle, a circle, a square, and so on. Each of these classes has a member function <em>getArea()</em> that returns the area of the object.</p>
<p>Now suppose you plan to calculate the area by grouping a number of these elements together, and you want to calculate in a convenient way. One approach is to create an array that holds pointers to all the different objects. The array might be defined like this.</p>
<p>shape *ptrarr[100]; //array of 100 pointers to shapes</p>
<p>If you insert pointers to all the shapes into this array, you can then calculate area using a simple loop:</p>
<div style="text-align:left;" dir="ltr">
<div>
<pre> for(int j=0; j&lt;N; j++)
 cout &lt;&lt; ptrarr[j]-&gt;getArea() &lt;&lt; endl;</pre>
</div>
</div>
<p>This is an amazing capability: Completely different functions are executed by the same function call. If the pointer in <em>ptrarr</em> points to a square, the square function that returns area is called; if it points to a triangle, the triangle area function is called. This is called <strong>polymorphism</strong>, which means different forms. The functions have the same functionality, the getArea(), but different actual functions are called, depending on the contents of ptrarr[j]. Polymorphism is one of the key features of object-oriented programming, after classes and inheritance.</p>
<p>For the polymorphic approach to work, several conditions must be met.</p>
<ul>
<li>First, all the different classes of shapes, such as circle and triangles, must be descended from a single base class (called shape in Geometry).</li>
<li>Second, the getArea() function must be declared to be virtual in the base class.</li>
</ul>
<p><a id="Virtual_Member_Functions_Accessed_with_Pointers" name="Virtual_Member_Functions_Accessed_with_Pointers"></a></p>
<h4>Virtual Member Functions Accessed with Pointers</h4>
<p>Let’s make a single change in our program (BASEPOINT): We’ll place the keyword virtual in front of the declarator for the show() function in the base class. Here’s the listing for the resulting program,VIRTPOINT:</p>
<div style="text-align:left;" dir="ltr">
<div>
<pre>// virtpoint.cpp
// virtual functions accessed from pointer
#include
using namespace std;
////////////////////////////////////////////////////////////////
class Base //base class
{
public:
      virtual void show(){ cout &lt;&lt; "Base\n"; }
};
////////////////////////////////////////////////////////////////
class Derv1 : public Base //derived class 1
{
public:
      void show()
        { cout &lt;&lt; "Derv1\n"; }
};
////////////////////////////////////////////////////////////////
class Derv2 : public Base //derived class 2
{
public:
      void show()
           { cout &lt;&lt; "Derv2\n"; }
};
////////////////////////////////////////////////////////////////
int main()
{
Derv1 dv1; //object of derived class 1
Derv2 dv2; //object of derived class 2
Derv1 *pdv1;
Derv2 *pdv2;

Base* ptr; //pointer to base class
ptr = &amp;dv1; //put address of dv1 in pointer
ptr-&gt;show(); //execute show()

ptr = &amp;dv2; //put address of dv2 in pointer
ptr-&gt;show(); //execute show()

ptr = &amp;dv1; //put address of dv1 in pointer

if(dynamic_cast&lt;Derv1 *&gt;(ptr) !=0){
  pdv1 =  reinterpret_cast&lt;Derv1 *&gt;(ptr);
  pdv1-&gt;show();
}
ptr = &amp;dv2; //put address of dv2 in pointer
if(dynamic_cast&lt;Derv2 *&gt;(ptr) !=0){
  pdv2 =  reinterpret_cast&lt;Derv2 *&gt;(ptr);
  pdv2-&gt;show();
}

system("PAUSE");
return 0;
}</pre>
</div>
</div>
<p>The output of this program is</p>
<ul>
<li>Derv1</li>
<li>Derv2</li>
<li>Derv1</li>
<li>Derv2</li>
</ul>
<p>Now, as you can see, the member functions of the derived classes, not the base class, are executed. We change the contents of ptr from the address of Derv1 to that of Derv2, and the particular instance of show() that is executed also changes. So the same function call</p>
<div style="text-align:left;" dir="ltr">
<div>
<pre>ptr-&gt;show();</pre>
</div>
</div>
<p>executes different functions, depending on the contents of ptr. The rule is that the compiler selects the function based on the contents of the pointer ptr, not on the type of the pointer, as in BASEPOINT. This is shown in Figure below.</p>
<p><img src="http://wiki.msitprogram.net/CPP09/W1/M7/vpointeraccess.jpg" alt="vpointeraccess.jpg" /></p>
<p>You can use <strong>dynamic_cast</strong> operator to cast to a particular derived type for the polymorphic classes.</p>
<p><a id="Late_Binding" name="Late_Binding"></a></p>
<h4>Late Binding</h4>
<p>The astute reader may wonder how the compiler knows what function to compile. In BASEPOINT the compiler has no problem with the expression</p>
<div style="text-align:left;" dir="ltr">
<div>
<pre>ptr-&gt;show();</pre>
</div>
</div>
<p>It always compiles a call to the show() function in the base class. But in VIRTPOINT the compiler doesn’t know what class the contents of ptr may contain. It could be the address of an object of the Derv1 class or of the Derv2 class. Which version of draw() does the compiler call? In fact the compiler doesn’t know what to do, so it arranges for the decision to be deferred until the program is running. At runtime, when it is known what class is pointed to by ptr, the appropriate version of draw will be called. This is called <strong>late binding or dynamic binding</strong>.(Choosing functions in the normal way, during compilation, is called early binding or static binding.) Late binding requires some overhead but provides increased power and flexibility.</p>
<p>We’ll put these ideas to use in a moment, but first let’s consider a refinement to the idea of virtual functions.</p>
<p><a id="Abstract_Classes_and_Pure_Virtual_Functions" name="Abstract_Classes_and_Pure_Virtual_Functions"></a></p>
<h4>Abstract Classes and Pure Virtual Functions</h4>
<p>Think of the shape class. We’ll never make an object of the shape class; we’ll only make specific shapes such as circles and triangles. When we will never want to instantiate objects of a base class, we call it an <strong>abstract class</strong>. Such a class exists only to act as a parent of derived classes that will be used to instantiate objects. It may also provide an interface for the class hierarchy.</p>
<p>How can we make it clear to someone using our family of classes that we don’t want anyone to instantiate objects of the base class? We could just say this in the documentation, and count on the users of the class to remember it, but of course it’s much better to write our classes so that such instantiation is impossible. How can we can do that? By placing at least one pure virtual function in the base class. A pure virtual function is one with the expression =0 added to the declaration. This is shown in the VIRTPURE example.</p>
<div style="text-align:left;" dir="ltr">
<div>
<pre>// virtpure.cpp
// pure virtual function
#include
using namespace std;
////////////////////////////////////////////////////////////////
class Base //base class
{
public:
 virtual void show() = 0; //pure virtual function
};
////////////////////////////////////////////////////////////////
class Derv1 : public Base //derived class 1
{
public:
 void show()
  { cout &lt;&lt; “Derv1\n”; }
};
////////////////////////////////////////////////////////////////
class Derv2 : public Base //derived class 2
{
public:
 void show()
 { cout &lt;&lt; “Derv2\n”; }
};
////////////////////////////////////////////////////////////////
int main()
{
// Base bad; //can’t make object from abstract class
Base* arr[2]; //array of pointers to base class
Derv1 dv1; //object of derived class 1
Derv2 dv2; //object of derived class 2
arr[0] = &amp;dv1; //put address of dv1 in array
arr[1] = &amp;dv2; //put address of dv2 in array
arr[0]-&gt;show(); //execute show() in both objects
arr[1]-&gt;show();
return 0;
}</pre>
</div>
</div>
<p>Here the virtual function show() is declared as</p>
<p>virtual void show() = 0; // pure virtual function</p>
<p>The equal sign here has nothing to do with assignment; the value 0 is not assigned to anything. The =0 syntax is simply how we tell the compiler that a virtual function will be pure. Now if in main() you attempt to create objects of class Base, the compiler will complain that you’re trying to instantiate an object of an abstract class. It will also tell you the name of the pure virtual function that makes it an abstract class. Notice that, although this is only a declaration, you never need to write a definition of the base class show(), although you can if you need to.</p>
<p>Once you’ve placed a pure virtual function in the base class, you must override it in all the derived classes from which you want to instantiate objects. If a class doesn’t override the pure virtual function, it becomes an abstract class itself, and you can’t instantiate objects from it (although you might from classes derived from it). For consistency, you may want to make all the virtual functions in the base class pure. As you can see, we’ve made another, unrelated, change in VIRTPURE: The addresses of the member functions are stored in an array of pointers and accessed using array elements. This works in just the same way as using a single pointer. The output of VIRTPURE is the same as</p>
<p>VIRT:</p>
<ul>
<li>Derv1</li>
<li>Derv2</li>
</ul>
<p><a id="Virtual_Destructors" name="Virtual_Destructors"></a></p>
<h4>Virtual Destructors</h4>
<p>Base class <em>destructors</em> should always be <strong>virtual</strong>. Suppose you use <strong>delete</strong> with a <strong>base class pointer</strong> to a <strong>derived class object</strong> to <strong>destroy the derived-class object</strong>. If the base-class destructor is <strong>not virtual</strong> then delete, like a normal member function, calls the destructor for the base class, <strong>not</strong> the destructor for the derived class.</p>
<p><a id="Points_to_remember" name="Points_to_remember"></a></p>
<h3>Points to remember</h3>
<ul>
<li>The process of resolving a function call to an object is called binding</li>
<li>Associating an object to a function call at run-time is referred to as late binding.</li>
<li>A pointer of a base class can point to an object of any of its derived class.</li>
<li>The virtual keyword is used to declare a function as virtual.</li>
<li>Virtual functions that have no body are called pure virtual functions.</li>
<li>A class containing one or more pure virtual functions is called an abstract class.</li>
<li>Instances of an abstract class cannot be created but pointers to it can created.</li>
<li>Static polymorphism involves binding of a function on the basis of the number, type and sequence of its arguments.</li>
<li>Function overloading is an example of static polymorphism because functions can be bound to the calls at compile time.</li>
<li>A function exhibits dynamic polymorphism when it exists in more than one form, and calls to its various forms are resolved dynamically when the program executed.</li>
<li>Static binding is considered to be more efficient while dynamic binding is more flexible.</li>
</ul>
<p><a id="Steps_to_attack_the_problem_sets" name="Steps_to_attack_the_problem_sets"></a></p>
<h2>Steps to attack the problem sets</h2>
<ul>
<li>Step 1: Read the <a title="CPP09:W1-M7" href="http://wiki.msitprogram.net/index.php/CPP09:W1-M7#Introduction">Introduction</a> and try sample programs given in the introduction(You can copy paste the programs)</li>
<li>Step 2: Go through the given PPT on Polymorphism and try sample problems given in the PPT.(you can copy paste the programs from the PPT)</li>
<li>Step 3: Go through the additional resources give for further clarification.</li>
<li>Step 4: Attack the problem sets in the given order(Problem Set A and then Problem Set B).</li>
<li>Step 5: If you are not clear with the problem sets then contact your respective mentor for clarification.</li>
</ul>
<p>Spend at least 2-3 hours from Step 1 to Step 3.</p>
<p>Don&#8217;t get confused with the example given in PPT and in the introduction part of this Module for shapes. In PPT, Shapes are used with respect to point in a plane and in introduction part shapes is used with respect to Geometry(area, sides, circumference etc).</p>
<p><a id="Resources" name="Resources"></a></p>
<h2>Resources</h2>
<p>References:</p>
<ul>
<li><a title="http://www.cplusplus.com/doc/tutorial/polymorphism/" rel="nofollow" href="http://www.cplusplus.com/doc/tutorial/polymorphism/">Polymorphism &#8212; C Plus Plus .com</a></li>
<li><a title="http://publib.boulder.ibm.com/infocenter/lnxpcomp/v7v91/index.jsp?topic=/com.ibm.vacpp7l.doc/language/ref/clrc05keyword_dynamic_cast.htm" rel="nofollow" href="http://publib.boulder.ibm.com/infocenter/lnxpcomp/v7v91/index.jsp?topic=/com.ibm.vacpp7l.doc/language/ref/clrc05keyword_dynamic_cast.htm">Reinterpret_Cast and Dynamic_Cast</a></li>
</ul>
<p><a id="Problem_Sets" name="Problem_Sets"></a></p>
<h2>Problem Sets</h2>
<p><a id="Problem_Set_A" name="Problem_Set_A"></a></p>
<h3>Problem Set A</h3>
<p><strong>1. </strong> Create a set of classes of Shapes (triangle, quadrilateral, circle) with the following inheritance relationship.</p>
<p><img src="http://wiki.msitprogram.net/CPP09/W1/M7/shapes.jpg" alt="shapes.jpg" /></p>
<p>Declare and define the classes as</p>
<ul>
<li>Shapes&#8211; Abstract base class.
<ul>
<li>Triangle &#8212; Abstract derived class with base class as Shapes
<ul>
<li>IsoscelesTriangle &#8212; derived class with base class as Triangle.(Attribute with two sides)</li>
<li>EquilateralTriangle &#8212; derived class with base class as Triangle(Attribute with one side)</li>
</ul>
</li>
<li>Quadrilateral &#8211;Abstract derived class with base class as Shapes.
<ul>
<li>Rectangle &#8212; derived class with base class as Quadrilateral.(Attribute with two sides&#8211; length and breadth)</li>
<li>Square &#8212; derived class with base class as Quadrilateral.(Attribute with one side)</li>
<li>Rhombus &#8212; derived class with base class as Quadrilateral. (Attribute with two sides&#8211; length and breadth)</li>
</ul>
</li>
<li>Circle &#8212; Derived class with base class as Shapes. (Attribute with radius)</li>
</ul>
</li>
</ul>
<p>Use the following declarations for the abstract class and the test main function. Write the code where ever necessary.</p>
<div style="text-align:left;" dir="ltr">
<div>
<pre>#include
using namespace std;
////////////////////////////////////////////////////////////////
class Shapes //Abstract base class
{
public:
      virtual double getArea()=0; //Calculates the Area and returns the area
      virtual double getPerimeter()=0; //Calculates the perimeter and return the perimeter.
      virtual void getData()=0; //Take input from the user and store in the state of the object.
      virtual ~Shapes(){};
};

class Triangle : public Shapes  //Derived Abstract class
{
//Write your code here
};

class Quadrilateral : public Shapes //Derived Abstract class
{
public:
//Write your code here
};

//Write your code here to declare and define other classes stated

int main(){

//Write your code here to declare an array pointer of Shapes[6].

//Write a Loop for the Menu to create an instance of the object
// andget the input from the user for the selected Shape
//and add the pointer to the Shapes array.

//Write a Loop to Print the Area and Perimeter of the array shapes.

   system("PAUSE");
}</pre>
</div>
</div>
<p>Display a Menu Interface to the user to Create an instance of the Object. The Menu should be like.</p>
<ul>
<li>Create an Instance of
<ul>
<li>Triangle
<ul>
<li>Create IsoscelesTriangle</li>
<li>Create EquilateralTriangle</li>
</ul>
</li>
<li>Quadrilateral
<ul>
<li>Create Rectangle</li>
<li>Create Square</li>
<li>Create Rhombus</li>
</ul>
</li>
<li>Create Circle</li>
</ul>
</li>
</ul>
<p>Create should create an instance of the derived class selected and then call the getData() function of that class and store that instance in the array of Shapes(Base Class).</p>
<p><strong>You can add constructors for the derived classes with default values</strong>.</p>
<p>Write a test main function to take the input from the user for all the shapes and store them in a array, then print the area and perimeter of the class.</p>
<p>Refer: <a title="http://www.math.com/tables/geometry/index.htm" rel="nofollow" href="http://www.math.com/tables/geometry/index.htm">http://www.math.com/tables/geometry/index.htm</a></p>
<p><strong>All the measurements is in Centimeters</strong></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/techonhand.wordpress.com/31/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/techonhand.wordpress.com/31/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/techonhand.wordpress.com/31/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/techonhand.wordpress.com/31/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/techonhand.wordpress.com/31/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/techonhand.wordpress.com/31/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/techonhand.wordpress.com/31/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/techonhand.wordpress.com/31/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/techonhand.wordpress.com/31/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/techonhand.wordpress.com/31/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/techonhand.wordpress.com/31/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/techonhand.wordpress.com/31/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/techonhand.wordpress.com/31/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/techonhand.wordpress.com/31/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=techonhand.wordpress.com&amp;blog=9884312&amp;post=31&amp;subd=techonhand&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://techonhand.wordpress.com/2009/10/11/polymorphism/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/a93e36381d7b6e452b246a24496e3884?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">seshhu143</media:title>
		</media:content>

		<media:content url="http://wiki.msitprogram.net/CPP09/W1/M7/pointeraccess.jpg" medium="image">
			<media:title type="html">pointeraccess.jpg</media:title>
		</media:content>

		<media:content url="http://wiki.msitprogram.net/CPP09/W1/M7/vpointeraccess.jpg" medium="image">
			<media:title type="html">vpointeraccess.jpg</media:title>
		</media:content>

		<media:content url="http://wiki.msitprogram.net/CPP09/W1/M7/shapes.jpg" medium="image">
			<media:title type="html">shapes.jpg</media:title>
		</media:content>
	</item>
		<item>
		<title>Multiple Inheritance</title>
		<link>http://techonhand.wordpress.com/2009/10/11/multiple-inheritance/</link>
		<comments>http://techonhand.wordpress.com/2009/10/11/multiple-inheritance/#comments</comments>
		<pubDate>Sun, 11 Oct 2009 11:17:51 +0000</pubDate>
		<dc:creator>seshhu143</dc:creator>
				<category><![CDATA[C ++]]></category>

		<guid isPermaLink="false">http://techonhand.wordpress.com/?p=29</guid>
		<description><![CDATA[Learning Objectives At the end of this Module, you will be able to: Understand the concept of multiple inheritance Identify and solve the ambiguities that arise in multiple inheritance. Define Virtual base class State the order of invocation of constructors and destructors Introduction Multiple Inheritance Multiple Inheritance is the concept where a subclass inherits properties [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=techonhand.wordpress.com&amp;blog=9884312&amp;post=29&amp;subd=techonhand&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<h2>Learning Objectives</h2>
<p>At the end of this Module, you will be able to:</p>
<ul>
<li>Understand the concept of multiple inheritance</li>
<li>Identify and solve the ambiguities that arise in multiple inheritance.</li>
<li>Define Virtual base class</li>
<li>State the order of invocation of constructors and destructors</li>
</ul>
<h2>Introduction</h2>
<h3>Multiple Inheritance</h3>
<p><strong>Multiple Inheritance</strong> is the concept where a subclass inherits properties from multiple base classes. A familiar example of multiple inheritance is the child inheriting the characteristics of the parents.</p>
<p><img src="http://wiki.msitprogram.net/CPP09/W1/M6/father_mother.jpg" alt="father_mother.jpg" /></p>
<p>You can derive a class from any number of base classes. Deriving a class from more than one direct base class is called multiple inheritance.</p>
<p>In the following example, classes A, B, and C are direct base classes for the derived class X:</p>
<p>The following inheritance graph describes the inheritance relationships of the above example. An arrow points to the direct base class of the class at the tail of the arrow:</p>
<div style="text-align:left;" dir="ltr">
<div>
<pre>class A { /* ... */ };
class B { /* ... */ };
class C { /* ... */ };
class X : public A, private B, public C { /* ... */ };</pre>
</div>
</div>
<p><img src="http://wiki.msitprogram.net/CPP09/W1/M6/abc_x.jpg" alt="abc_x.jpg" /></p>
<h3>Ambiguities in Multiple Inheritance</h3>
<p>When a class inherits from multiple base classes, a whole lot of ambiguities creep in. For example , what happens when two base classes contain a function of the same name?</p>
<p>For example given below &#8211;&gt; Class A , Class B has Member functions disp() <strong>(to display the attributes of the class)</strong> and Class C inherits A and B.</p>
<div style="text-align:left;" dir="ltr">
<div>
<pre>
class A {
  /* ... */
  public:
  void disp(void);
  };
class B {
 /* ... */
 public:
  void disp(void);
};
class C : public A, private B {
/* ... */
};

void main(){
 C c;
 C.disp();//Ambiguous
}</pre>
</div>
</div>
<p>Here the reference to disp() is ambiguous because the compiler does not know whether disp() refers to the member in class base1 or base2. This ambiguity can be resolved using the scope resolution operator as illustrated hereunder.</p>
<div style="text-align:left;" dir="ltr">
<div>
<pre>
class C : public A, private B {
/* ... */
public:
   void disp(void){
      A.disp();
      B.disp();
   }
};
void main(){
 C c;
 c.disp();
}</pre>
</div>
</div>
<p>This ambiguity can also be resolved by overriding as illustrated hereunder.</p>
<div style="text-align:left;" dir="ltr">
<div>
<pre>
void main(){
 C c;
 c.A::disp();
 c.B.::disp();
}</pre>
</div>
</div>
<p>Another <strong>ambiguity that arises in multiple inheritance</strong> is the possibility of the derived class having <strong>multiple copies of the same base class</strong>. Consider the following diagram.</p>
<p><img src="http://wiki.msitprogram.net/CPP09/W1/M6/bl_d.jpg" alt="bl_d.jpg" /></p>
<div style="text-align:left;" dir="ltr">
<div>
<pre>class L { /* ... */ };                  // indirect base class
class B2 : public L { /* ... */ };
class B3 : public L { /* ... */ };
class D : public B2, public B3 { /* ... */ }; // valid</pre>
</div>
</div>
<p>In the above example, class D inherits the indirect base class L once through class B2 and once through class B3. However, this may lead to ambiguities because two objects of class L exist, and both are accessible through class D. You can avoid this ambiguity by referring to class L using a qualified class name. For example:</p>
<div style="text-align:left;" dir="ltr">
<div>
<pre>B2::L</pre>
</div>
</div>
<p>or</p>
<div style="text-align:left;" dir="ltr">
<div>
<pre>B3::L</pre>
</div>
</div>
<p>You can also avoid this ambiguity by using the base specifier virtual to declare a base class.</p>
<h3>Virtual Base Classes</h3>
<p>The principle behind virtual base classes is very simple. When the same class is inherited more than once via multiple paths, multiple copies of the base class members are created in memory. By declaring the base class inheritance as <strong>virtual</strong>, only one copy of the base class is inherited. A base class inheritance can be specified as virtual using <strong>virutal qualifier</strong>.</p>
<p>The class definitions would be modified as follows</p>
<div style="text-align:left;" dir="ltr">
<div>
<pre>class L { /* ... */ }; // indirect base class
class B1 : virtual public L { /* ... */ };
class B2 : virtual public L { /* ... */ };
class D : public B1, public B2 { /* ... */ }; // valid</pre>
</div>
</div>
<h3>Invocation of Constructors and Destructors</h3>
<ul>
<li>Constructors are invoked in the following order:
<ul>
<li>Virtual base class constructors &#8212; in the order of inheritance.</li>
<li>Non-Virtual base class constructors &#8212; in the order of inheritance.</li>
<li>Member objects constructors &#8212; in the order of declaration</li>
<li>Derived class constructor.</li>
</ul>
</li>
<li>Destructor are invoked in the reverse order</li>
</ul>
<h2>Problem Sets</h2>
<h3>Problem Set A</h3>
<p><strong>1.</strong> Create a set of classes named <strong>A, B, C, D, E, F, &amp; G</strong> with the following inheritance relationship:</p>
<p><img src="http://wiki.msitprogram.net/CPP09/W1/M6/pa1.jpg" alt="pa1.jpg" /></p>
<p>Give each class a constructor and destructor only that print simple trace messages to the screen(&#8216;<em>like</em> Constructor A or Destructor A ). <strong>Use non-virtual inheritance</strong>. Test each of the classes individually by creating objects of each type in a Test Program. Study the constructor and destructor trace messages and submit the trace.<br />
The Trace document should contain the trace output for each of the classes individually by creating objects of each type.</p>
<pre>Name the program as: PA1_NonVirtualInheritance.cpp
Name the Trace Document as: PA1_NonVirtualInheritance.doc
</pre>
<h3>Problem Set B</h3>
<p><strong>1.</strong> Create a set of classes named <strong>A, B, C, D, E, F, &amp; G</strong> with the following inheritance relationship:</p>
<p><img src="http://wiki.msitprogram.net/CPP09/W1/M6/pa1.jpg" alt="pa1.jpg" /></p>
<p>Give each class a constructor and destructor only that print simple trace messages to the screen(&#8216;<em>like</em> Constructor A or Destructor A ). <strong>Use virtual qualifier in the inheritance</strong> wherever necessary. Test each of the classes individually by creating objects of each type in a Test Program. Study the constructor and destructor trace messages and submit the trace.<br />
The Trace document should contain the trace output for each of the classes individually by creating objects of each type.</p>
<pre>Name the program as: PB1_VirtualInheritance.cpp
Name the Trace Document as: PB1_VirtualInheritance.doc
</pre>
<h3>Problem Set C</h3>
<p><strong>1. </strong> <strong>Thomson</strong> publishing company markets both books and video-cassette. Create a class called <strong>Publication</strong> that stores the <em>title</em>(string) and <em>price</em>(float) of a publication. From this class derive two classes: <strong>Book</strong> which adds a page <strong>count</strong> (type int); and <strong>VideoCassette</strong>, which adds a <em><strong>playing time</strong></em> (type int) in minutes. Each of these classes should have a <em><strong>getdata()</strong></em> function to get its data from the user and a <em><strong>putdata()</strong></em>function to display its data.</p>
<p>Add another base class <strong>Sales</strong> that holds an array of <strong>three floats</strong> so that it can record the sales of a particular publication for the last three months. Include a <strong>getdata()</strong> function to get three sales amounts from the user, and a <strong>putdata()</strong> function to display the sales figures. Alter the <strong>book </strong>and<strong>tape</strong> classes so that they are derived from both <strong>Publication</strong> and <strong>Sales</strong>. An object of class book or tape should input or output sales along with its other data. Write a <strong>main()</strong> function to create a book object and a tape object and which will update their corresponding member data along with the sales made.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/techonhand.wordpress.com/29/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/techonhand.wordpress.com/29/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/techonhand.wordpress.com/29/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/techonhand.wordpress.com/29/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/techonhand.wordpress.com/29/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/techonhand.wordpress.com/29/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/techonhand.wordpress.com/29/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/techonhand.wordpress.com/29/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/techonhand.wordpress.com/29/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/techonhand.wordpress.com/29/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/techonhand.wordpress.com/29/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/techonhand.wordpress.com/29/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/techonhand.wordpress.com/29/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/techonhand.wordpress.com/29/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=techonhand.wordpress.com&amp;blog=9884312&amp;post=29&amp;subd=techonhand&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://techonhand.wordpress.com/2009/10/11/multiple-inheritance/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/a93e36381d7b6e452b246a24496e3884?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">seshhu143</media:title>
		</media:content>

		<media:content url="http://wiki.msitprogram.net/CPP09/W1/M6/father_mother.jpg" medium="image">
			<media:title type="html">father_mother.jpg</media:title>
		</media:content>

		<media:content url="http://wiki.msitprogram.net/CPP09/W1/M6/abc_x.jpg" medium="image">
			<media:title type="html">abc_x.jpg</media:title>
		</media:content>

		<media:content url="http://wiki.msitprogram.net/CPP09/W1/M6/bl_d.jpg" medium="image">
			<media:title type="html">bl_d.jpg</media:title>
		</media:content>

		<media:content url="http://wiki.msitprogram.net/CPP09/W1/M6/pa1.jpg" medium="image">
			<media:title type="html">pa1.jpg</media:title>
		</media:content>

		<media:content url="http://wiki.msitprogram.net/CPP09/W1/M6/pa1.jpg" medium="image">
			<media:title type="html">pa1.jpg</media:title>
		</media:content>
	</item>
		<item>
		<title>Inheritance</title>
		<link>http://techonhand.wordpress.com/2009/10/11/inheritance/</link>
		<comments>http://techonhand.wordpress.com/2009/10/11/inheritance/#comments</comments>
		<pubDate>Sun, 11 Oct 2009 11:15:31 +0000</pubDate>
		<dc:creator>seshhu143</dc:creator>
				<category><![CDATA[C ++]]></category>

		<guid isPermaLink="false">http://techonhand.wordpress.com/?p=27</guid>
		<description><![CDATA[Learning Objectives At the end of this module, you will be able to Understand the implementation of inheritance in C++ Override the base class members Access overridden base class members using the scope resolution operator Understand the concept of base class initialization Introduction Inheritance The philosophy behind inheritance is to portray things as they exist [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=techonhand.wordpress.com&amp;blog=9884312&amp;post=27&amp;subd=techonhand&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<h2>Learning Objectives</h2>
<p>At the end of this module, you will be able to</p>
<ul>
<li>Understand the implementation of inheritance in C++</li>
<li>Override the base class members</li>
<li>Access overridden base class members using the scope resolution operator</li>
<li>Understand the concept of base class initialization</li>
</ul>
<p><a id="Introduction" name="Introduction"></a></p>
<h2>Introduction</h2>
<p><a id="Inheritance" name="Inheritance"></a></p>
<h3>Inheritance</h3>
<p>The philosophy behind inheritance is to portray things as they exist in the real world. As inheritance is found in real world, it is important feature of OO programming. Inheritance has many advantages, the most important of them being the <em>resuability</em> of code. Once a class is defined and debugged, it can be used to create new subclasses. The reuse of existing class saves time and effort.</p>
<p>The Class from which another class is derived is called the <strong>base class</strong>. The class which inherits the properties of the base class is called the <strong>derived class</strong>. Each instance of the derived class includes all the members of the base class. Since the derived class inherits all properties of the base class, the derived class has a larger set of properties than its base class. However, the derived class may override some or all the properties of the base class.</p>
<p>Any class can be a base class. More than one class can be derived from a single base class, and a derived class can be a base class to another.</p>
<p>if class d1 is inherited from class b1, then the syntax for declaring class derived is</p>
<p>class d1::public b1</p>
<p>An object defined outside the class can access only the public members of the class. Therefore, private members of a class cannot be directly accessed from outside the class. This holds true even for a derived class. Even though the derived class inherits all the members data and functions from the base class, private members of the base class are not directly accessible from the derived class. The idea behind this is never to compromise on encapsulation implemented through data hiding.</p>
<p>The protected members of a class can be accessed by its members functions, or within any class derived from it. Protected members behave like public members with respect to the derived class and like private members with respect to the rest of the program.</p>
<p><a id="Overriding_Base_Class_Members" name="Overriding_Base_Class_Members"></a></p>
<h4>Overriding Base Class Members</h4>
<p>A base class members can be overridden by defining a derived class member with the same name as that of the base class member.</p>
<p>If the function exists in both the derived class and the base class then.</p>
<ul>
<li>If the function is invoked from an Object of the derived class, then the function in the derived class is executed.</li>
<li>If the function is invoked from an Object of the base class, then the base class member function is invoked.</li>
</ul>
<p><a id="Inheritance_Example_in_Real_World" name="Inheritance_Example_in_Real_World"></a></p>
<h4>Inheritance Example in Real World</h4>
<p>In a Banking System, Manager, Officers, Clerk have some common and as well as special behavior (specific tasks/actions). The commonality is that they are all employees of the Bank. A generalized class “Employee_GeneralizedClass” could be used to represent the commonality among Object classes.</p>
<p>The generalization is often referred to as inheritance, and the generalized class as parent class. inheritance is a means of specifying hierarchical relationships between object classes.</p>
<p><a id="Points_to_Remember" name="Points_to_Remember"></a></p>
<h4>Points to Remember</h4>
<ul>
<li>The class from which a subclass is derived is referred to as the <em>base class&#8217;.</em></li>
<li>Base class constructors and destructors are not inherited by the derived class.</li>
<li>Derived class constructors must explicitly call the base class constructors with appropriate parameters.</li>
<li>Destructors are invoked in the reverse order.</li>
</ul>
<p><a id="Resources" name="Resources"></a></p>
<p>Inheritance:</p>
<ul>
<li><a title="http://www.cplusplus.com/doc/tutorial/inheritance.html" rel="nofollow" href="http://www.cplusplus.com/doc/tutorial/inheritance.html">http://www.cplusplus.com/doc/tutorial/inheritance.html</a></li>
<li><a title="http://www.csse.monash.edu.au/~jonmc/CSE2305/Topics/05.09.Inheritance/html/text.html#inheritance_in_c" rel="nofollow" href="http://www.csse.monash.edu.au/%7Ejonmc/CSE2305/Topics/05.09.Inheritance/html/text.html#inheritance_in_c">http://www.csse.monash.edu.au/~jonmc/CSE2305/Topics/05.09.Inheritance/html/text.html#inheritance_in_c</a></li>
</ul>
<p>Protected:</p>
<ul>
<li><a title="http://www.parashift.com/c++-faq-lite/basics-of-inheritance.html#faq-19.6" rel="nofollow" href="http://www.parashift.com/c++-faq-lite/basics-of-inheritance.html#faq-19.6">http://www.parashift.com/c++-faq-lite/basics-of-inheritance.html#faq-19.6</a></li>
</ul>
<p><a id="Steps_to_attack_the_problem_sets" name="Steps_to_attack_the_problem_sets"></a></p>
<h2>Steps to attack the problem sets</h2>
<ul>
<li>Step 1: Read the <a title="CPP09:W1-M5" href="http://wiki.msitprogram.net/index.php/CPP09:W1-M5#Introduction">Introduction</a></li>
<li>Step 2: Go through the Videos given in the <a title="CPP09:W1-M5" href="http://wiki.msitprogram.net/index.php/CPP09:W1-M5#Resources">Resources</a>.</li>
<li>Step 3: Go through the given PPT on Inheritance and try sample problems given in the PPT.(you can copy paste the programs from the PPT)</li>
<li>Step 4: Go through the additional resources give for further clarification.</li>
<li>Step 5: Attack the problem sets in the given order(Problem Set A and then Problem Set B).</li>
<li>Step 6: If you are not clear with the problem sets then contact your respective mentor for clarification.</li>
</ul>
<p>Spend at least 2 hours from Step 1 to Step 4.</p>
<p><a id="Problem_Sets" name="Problem_Sets"></a></p>
<h2>Problem Sets</h2>
<p><a id="Problem_Set_A" name="Problem_Set_A"></a></p>
<h3>Problem Set A</h3>
<p><strong>1. </strong> Draw an inheritance hierarchy for classes <strong>Quadrilateral</strong>, <em>TRapezoid</em>, <em>Parallelogram</em>, <em>Rectangle</em> and <em>Square</em>. Use <strong>Quadrilateral</strong> as the base class of the hierarchy. Make the hierarchy as deep as possible.</p>
<p>The diagrams should include the state and behavior for each class.</p>
<p>Example Image for Inheritance is:</p>
<p><img src="http://wiki.msitprogram.net/CPP09/W1/M5/InheritanceExample.jpg" alt="InheritanceExample.jpg" /></p>
<pre>Name the document as : PA1_Quadrilateral.doc
</pre>
<p><strong>2. </strong>Draw an inheritance hierarchy for classes <strong>Shapes</strong>. <em>Circle, Square, Triangle and Quadrilateral</em>(described in previous task). Use the Shapes as the base class for the hierarchy. Make the hierarchy as deep as possible.</p>
<p>The diagrams should include the state and behavior for each class. Refer to the image given in PA1.</p>
<p>Refer: To the PPT given in the resources for inheritance.</p>
<pre>Name the document as : PA2_Shapes.doc
</pre>
<p><a id="Problem_Set_B" name="Problem_Set_B"></a></p>
<h3>Problem Set B</h3>
<p><strong>1. </strong> (<strong>Account</strong> Inheritance Hierarchy) Create an inheritance hierarchy that a bank might use to represent customers&#8217; bank accounts. All customers at this bank can deposit (i.e., credit) money into their accounts and withdraw (i.e., debit) money from their accounts. More specific types of accounts also exist. Savings accounts, for instance, earn interest on the money they hold. Checking accounts, for instance, charge a fee per transaction (i.e., credit or debit). Current accounts, on other hand, has overdraft(Negative balance) facility to withdraw the money.</p>
<p>Create an inheritance hierarchy containing base class <strong>Account</strong> and derived classes <strong>SavingsAccount</strong><span style="font-weight:bold;">, </span><strong>CheckingAccount</strong> and <strong>CurrentAccount</strong> that inherit from class <strong>Account</strong>. Base class <strong>Account</strong> should include <strong>one data member</strong> of type double to represent the <strong>account balance</strong>. The class should provide a constructor that receives an initial balance and uses it to initialize the data member. The constructor should validate the initial balance to ensure that it is greater than or equal to 0.0. If not, the balance should be set to 0.0 and the constructor should display an error message, indicating that the initial balance was invalid. The class should provide three member functions. Member function <strong>credit</strong> should add an amount to the current balance. Member function <strong>debit</strong> should withdraw money from the Account and ensure that the debit amount does not exceed the Account&#8217;s balance. If it does, the balance should be left unchanged and the function should print the message &#8220;Debit amount exceeded account balance.&#8221; Member function <strong>getBalance</strong> should return the current balance.</p>
<p>Derived class <strong>SavingsAccount</strong> should inherit the functionality of an <strong>Account</strong>, but also include a <strong>data member</strong> of type double indicating the <strong>interest rate</strong> (percentage) assigned to the Account. <strong>SavingsAccount&#8217;s </strong>constructor should receive the initial balance, as well as an initial value for the <strong>SavingsAccount&#8217;s</strong> interest rate. <strong>SavingsAccount</strong> should provide a <strong>public</strong> member function <strong>calculateInterest</strong> that returns a double indicating the amount of interest earned by an account. Member function <strong>calculateInterest</strong> should determine this amount by multiplying the interest rate by the account balance. [Note: SavingsAccount should inherit member functions credit and debit as is without redefining them.]</p>
<p>Derived class <strong>CheckingAccount</strong> should inherit from base class <strong>Account</strong> and include an additional <strong>data member</strong> of type double that represents the <strong>fee charged per</strong> transaction. <strong>CheckingAccount&#8217;s</strong> constructor should receive the initial balance, as well as a parameter indicating a fee amount. Class <strong>CheckingAccount</strong> should redefine member functions <strong>credit</strong> and <strong>debit</strong> so that they subtract the fee from the account balance whenever either transaction is performed successfully. <strong>CheckingAccount&#8217;s</strong> versions of these functions should invoke the base-class <strong>Account</strong> version to perform the updates to an <strong>account balance</strong>. <strong>CheckingAccount&#8217;s</strong> debit function should charge a fee only if money is actually withdrawn (i.e., the debit amount does not exceed the account balance). [Hint: Define Account's debit function so that it returns a bool indicating whether money was withdrawn. Then use the return value to determine whether a fee should be charged.]</p>
<p>Derived class <strong>CurrentAccount</strong> should inherit the functionality of an <strong>Account</strong>, but also include a <strong>data member</strong> of type double indicating the <strong>maximum overdraft limit</strong> (percentage) assigned to the Account. <strong>CurrentAccount&#8217;s </strong>constructor should receive the initial balance, as well as an initial value for the <strong>CurrentAccount&#8217;s</strong> maximum overdraft limit. <strong>CurrentAccount</strong> should redefine member function <strong>debit, </strong>so that the account holder can withdraw money upto a maximum of overdraft limit if the balance is below 0. [Note: An <strong>overdraft</strong> occurs when withdrawals from a bank account exceed the available balance which gives the account a negative balance]</p>
<p>After defining the classes in this hierarchy, write a Test program that creates objects of <strong>each class</strong> and <strong>tests their member functions</strong>. For Example: <strong>Add interest</strong> to the SavingsAccount object by first invoking its calculateInterest function, then passing the returned interest amount to the object&#8217;s <strong>credit function</strong>.</p>
<p>You can write the <strong>class declarations in separate header files&#8217;<em>as given in the example of the PPT and</em></strong><em>definitions in separate CPP file<strong>.<br />
</strong></em></p>
<p><strong>Use the Project in Dev C++ (File-&gt;New-&gt;Project) to compile and execute the programs</strong></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/techonhand.wordpress.com/27/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/techonhand.wordpress.com/27/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/techonhand.wordpress.com/27/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/techonhand.wordpress.com/27/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/techonhand.wordpress.com/27/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/techonhand.wordpress.com/27/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/techonhand.wordpress.com/27/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/techonhand.wordpress.com/27/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/techonhand.wordpress.com/27/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/techonhand.wordpress.com/27/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/techonhand.wordpress.com/27/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/techonhand.wordpress.com/27/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/techonhand.wordpress.com/27/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/techonhand.wordpress.com/27/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=techonhand.wordpress.com&amp;blog=9884312&amp;post=27&amp;subd=techonhand&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://techonhand.wordpress.com/2009/10/11/inheritance/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/a93e36381d7b6e452b246a24496e3884?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">seshhu143</media:title>
		</media:content>

		<media:content url="http://wiki.msitprogram.net/CPP09/W1/M5/InheritanceExample.jpg" medium="image">
			<media:title type="html">InheritanceExample.jpg</media:title>
		</media:content>
	</item>
		<item>
		<title>Operator Overloading</title>
		<link>http://techonhand.wordpress.com/2009/10/11/operator-overloading/</link>
		<comments>http://techonhand.wordpress.com/2009/10/11/operator-overloading/#comments</comments>
		<pubDate>Sun, 11 Oct 2009 11:12:52 +0000</pubDate>
		<dc:creator>seshhu143</dc:creator>
				<category><![CDATA[C ++]]></category>

		<guid isPermaLink="false">http://techonhand.wordpress.com/?p=24</guid>
		<description><![CDATA[Learning Objectives Objective is to better understand Constructor Destructor Operator Overloading Dynamic Memory Allocation and also gain additional practice with classes Resources http://www.fredosaurus.com/notes-cpp/newdelete/50dynamalloc.html http://www.fredosaurus.com/notes-cpp/newdelete/55dynexample.html Problem Sets Problem Set A 1. Consider a polynomial with integer coefficients, for instance 5x3 -4 x2 + 5. We can represent this polynomial by array of integers. The 0th element [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=techonhand.wordpress.com&amp;blog=9884312&amp;post=24&amp;subd=techonhand&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<h2>Learning Objectives</h2>
<p>Objective is to better understand</p>
<ol>
<li>Constructor</li>
<li>Destructor</li>
<li>Operator Overloading</li>
<li>Dynamic Memory Allocation</li>
</ol>
<p>and also gain additional practice with classes</p>
<p><a id="Resources" name="Resources"></a></p>
<h2>Resources</h2>
<ul>
<li><a title="http://www.fredosaurus.com/notes-cpp/newdelete/50dynamalloc.html" rel="nofollow" href="http://www.fredosaurus.com/notes-cpp/newdelete/50dynamalloc.html">http://www.fredosaurus.com/notes-cpp/newdelete/50dynamalloc.html</a></li>
<li><a title="http://www.fredosaurus.com/notes-cpp/newdelete/55dynexample.html" rel="nofollow" href="http://www.fredosaurus.com/notes-cpp/newdelete/55dynexample.html">http://www.fredosaurus.com/notes-cpp/newdelete/55dynexample.html</a></li>
</ul>
<p><a id="Problem_Sets" name="Problem_Sets"></a></p>
<h2>Problem Sets</h2>
<p><a id="Problem_Set_A" name="Problem_Set_A"></a></p>
<h3>Problem Set A</h3>
<p><strong>1. </strong>Consider a polynomial with integer coefficients, for instance 5x<sup>3</sup> -4 x<sup>2</sup> + 5. We can represent this polynomial by array of integers. The 0<sup>th</sup> element of the array is the coefficient of the x<sup>0</sup> term (5 in our example), the 1st element of the array is the coefficient of the x<sup>1</sup> term (0 in our example), the 2<sup>nd</sup> element of the array is the coefficient of the x<sup>2</sup> term (-4 in our example), etc. The size of the array determines how large a degree the polynomial can have: a polynomial with degree d will need an array with at least d+ 1 elements. Note that the actual degree of the polynomial may be smaller than (size of vector &#8211; 1), since some of the higher order terms may have zero coefficients.<br />
In this problem set, you will implement a Polynomial class. The polynomial class is having two members: array of integers and degree of polynomial as integer. It should support the following member functions.</p>
<ol>
<li><strong>Int degree()</strong> – Return the degree the of the polynomial</li>
<li><strong>Polynomial addition(const Polynomial &amp;p) </strong>– Returns the sum q + p, where q is the polynomial object whose member function is called. The degree of this sum will be at most max (degree(q), degree(p)).</li>
<li><strong>Polynomial sub(const Polynomial &amp;p) </strong>– Returns the subtraction q &#8211; p, where q is the polynomial object whose member function is called. The degree of this subtract will be at most max (degree(q), degree(p)).</li>
<li><strong>Polynomial multiply(const Polynomial&amp;p)</strong> &#8211; Returns the product qp, where q is the polynomial object whose member function is called. The degree of this sum will be exactly degree(q) + degree(p).</li>
<li><strong>bool equal(const Polynomial&amp;p)</strong> &#8211; Returns true if q is the same polynomial as p, and false otherwise, where q is the polynomial object whose member function is called. Two polynomials are equal if and only if (1) they have the same degree and (2) the coefficient of the terms of the same degree are equal.</li>
<li><strong>void read()</strong> &#8211; Reads the polynomial from cin. Your code should prompt the user for the degree of the polynomial, create a array with the correct size, and then use a loop to prompt and input each coefficient.</li>
<li><strong>void print()</strong> &#8211; Outputs the polynomial to cout. The polynomial should be printed out using a format that resembles the following: 5x^3 -4x^2 + 5.</li>
<li><strong>int evaluate(int x) </strong>- method to compute and return the polynomial evaluated at x</li>
<li>Additionally, the class should have the following constructors:
<ol>
<li><strong>Polynomial ()</strong> &#8211; The polynomial is initialized to be a degree 1 polynomial whose only coefficient is zero.</li>
<li><strong>Polynomial (int d)</strong> &#8211; The polynomial is initialized to be a degree d polynomial. That is, the array should have size d+1 whose coefficients are all zero.</li>
<li><strong>Polynomial (string s)</strong> – The polynomial is initialized to the string.</li>
<li><strong>Polynomial (const Polynomial &amp;p)</strong> – The polynomial is initialized to the polynomial passed (Know as copy constructor).</li>
</ol>
</li>
<li>The class should have the following operators overloaded
<ol>
<li><strong>=</strong></li>
<li><strong>==</strong></li>
<li><strong>+=</strong></li>
<li><strong>+</strong></li>
<li><strong>–</strong></li>
<li><strong>-=</strong></li>
<li><strong>*</strong></li>
<li><strong>*=</strong></li>
<li><strong>&lt;&lt;</strong> (as cout &lt;&lt; p)Refer: <a title="http://gethelp.devx.com/techtips/cpp_pro/10min/10min0400.asp" rel="nofollow" href="http://gethelp.devx.com/techtips/cpp_pro/10min/10min0400.asp">http://gethelp.devx.com/techtips/cpp_pro/10min/10min0400.asp</a></li>
<li><strong>&gt;&gt;</strong> (as cin &gt;&gt; p) Refer: <a title="http://www.csse.monash.edu.au/~jonmc/CSE2305/Topics/10.19.OpOverload/html/text.html#an_important_use_of_operator_overloading" rel="nofollow" href="http://www.csse.monash.edu.au/%7Ejonmc/CSE2305/Topics/10.19.OpOverload/html/text.html#an_important_use_of_operator_overloading">http://www.csse.monash.edu.au/~jonmc/CSE2305/Topics/10.19.OpOverload/html/text.html#an_important_use_of_operator_overloading</a></li>
</ol>
</li>
<li><strong>~Polynomial()</strong> &#8211; The class should have destructor to delete the memory allocated to the integer array</li>
</ol>
<p>Write a short test main function for polynomial class with the menu option like</p>
<pre>"What would you like to do?"
#Give a value to a polynomial(print the polynomial)
#Add the two polynomials
#Multiply the two polynomials
#Subtract the two polynomials
#Test equality of the two polynomial
#Evaluate the two polynomials for a given value of x
#Quit
</pre>
<p>You can add few more option to the menu if you like</p>
<pre>Name the program as: PA1_Polynomial.cpp
</pre>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/techonhand.wordpress.com/24/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/techonhand.wordpress.com/24/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/techonhand.wordpress.com/24/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/techonhand.wordpress.com/24/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/techonhand.wordpress.com/24/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/techonhand.wordpress.com/24/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/techonhand.wordpress.com/24/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/techonhand.wordpress.com/24/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/techonhand.wordpress.com/24/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/techonhand.wordpress.com/24/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/techonhand.wordpress.com/24/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/techonhand.wordpress.com/24/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/techonhand.wordpress.com/24/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/techonhand.wordpress.com/24/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=techonhand.wordpress.com&amp;blog=9884312&amp;post=24&amp;subd=techonhand&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://techonhand.wordpress.com/2009/10/11/operator-overloading/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/a93e36381d7b6e452b246a24496e3884?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">seshhu143</media:title>
		</media:content>
	</item>
		<item>
		<title>Creation and Behavior of software Objects</title>
		<link>http://techonhand.wordpress.com/2009/10/11/creation-and-behavior-of-software-objects/</link>
		<comments>http://techonhand.wordpress.com/2009/10/11/creation-and-behavior-of-software-objects/#comments</comments>
		<pubDate>Sun, 11 Oct 2009 11:06:25 +0000</pubDate>
		<dc:creator>seshhu143</dc:creator>
				<category><![CDATA[C ++]]></category>

		<guid isPermaLink="false">http://techonhand.wordpress.com/?p=19</guid>
		<description><![CDATA[Learning Objectives On successful completion of this module you should be able to: explain the purpose of a class constructor and identify a default constructor for a class explain the purpose of a class destructor and identify a default destructor for a class Apply function overloading Apply operator overloading code and use simple C++ classes [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=techonhand.wordpress.com&amp;blog=9884312&amp;post=19&amp;subd=techonhand&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<h3><a href="http://knowaboutcpp.blogspot.com/2009/10/creation-and-behavior-of-software.html"><br />
</a></h3>
<h2>Learning Objectives</h2>
<p>On successful completion of this module you should be able to:</p>
<ul>
<li>explain the purpose of a class constructor and identify a default constructor for a class</li>
<li>explain the purpose of a class destructor and identify a default destructor for a class</li>
<li>Apply function overloading</li>
<li>Apply operator overloading</li>
<li>code and use simple C++ classes using the following facilities:
<ul>
<li>public member functions and private data members</li>
<li>one or more constructors, including where appropriate, a default constructor</li>
<li>Overloading of functions</li>
<li>Operator overloading</li>
</ul>
</li>
</ul>
<h2>Introduction</h2>
<p><a id="The_Class" name="The_Class"></a></p>
<h3>The Class</h3>
<p>The class is a data type which specifies the data and the permissible operations on the instance of this class. The set of operations define the interface of the objects of the class. The class definition consists of zero or more data members, which together define the data part and zero or more member functions, which together define the interface. In addition, there are three levels of <strong>program access</strong>, that are associated with a class.</p>
<p>The members (data or functions) can be declared to be</p>
<ul>
<li><strong>Private</strong> members of the class are hidden and can be accessed only with in the class. Access to them members is denied from out side the class</li>
<li><strong>Protected</strong> members are accessible within the class and to the derived class(to be covered in next modules)</li>
<li><strong>Public</strong> members are visible outside the class and can be accessed from anywhere within the program.</li>
</ul>
<p>A class looks just like a <strong>struct</strong>, and indeed they are almost equivalent. By convention we always use class for <strong>abstract data types</strong> and only use <strong>struct</strong> for <strong>‘ordinary data structures’</strong> that don’t have member functions. The only difference between <strong>class</strong> and <strong>struct</strong> is that the default access control for members is <strong>private</strong> in the former and <strong>public</strong> in the latter.</p>
<p>A class consists of <em>data memebers</em> and <em>member functions</em>. Each having different program access level.</p>
<p>The <strong>data memebers</strong>, specify the attributes/state of the objects of the class. The data members define the name of the attributes and their type.</p>
<p>The <strong>member function</strong> describes behavior of an object-class and act on state (variables/fields) of an object-class. The member functions collectively define the interface of an object of a class. The special trait about member functions is they can access the private/protected data members (state variables/fields) of their class and manipulate them. No external functions can access the private/protected data members of a class.</p>
<p><a id="The_Class_Scope" name="The_Class_Scope"></a></p>
<h3>The Class Scope</h3>
<p>Every class defines the scope for the members in it. The data members of a class may be defined, before they are used in a member functions, or can be used in the member functions, and may be defined later in the class. The data members have the class scope, immaterial of where they are defined in the class.</p>
<h3>Constructor</h3>
<p>A constructor is also a member function, the first function called while creating an object. It could contain initializations to the variables of the object or calling other functions etc. The constructor by nature cannot return any value. The return has to be void. It can however take an argument list. The constructor has the same name as the class but having different argument list.</p>
<p>The constructor can be defined within the class definition or outside of it, just as any other member function definition. It can also be defined outside the class and made inline, just as other member functions can be</p>
<p>The constructor which takes no arguments is called the default constructor.</p>
<p><strong>Overloading constructor:</strong>When constructor are overloaded, the constructor must vary in the argument list. Upon object creation, that constructor for which there is match between the formal and the actual parameters, is invoked.</p>
<h4>Copy constructor</h4>
<p>A copy constructor is a special constructor in the C++ programming language used to create a new object as a copy of an existing object. First argument of such constructor is a reference to an object of the same type as being constructed (const or non-const), which might be followed by parameters of any type (all having default values).</p>
<p>Normally the compiler automatically creates a copy constructor for each class (known as an implicit copy constructor) but for special cases the programmer creates the copy constructor, known as an explicit copy constructor. In such cases, the compiler doesn&#8217;t create one.</p>
<p>Refer: <a title="http://www.fredosaurus.com/notes-cpp/oop-condestructors/copyconstructors.html" rel="nofollow" href="http://www.fredosaurus.com/notes-cpp/oop-condestructors/copyconstructors.html">http://www.fredosaurus.com/notes-cpp/oop-condestructors/copyconstructors.html</a></p>
<h3>Destructor</h3>
<p>The destructor destroys a previously created object. The destructor takes no arguments and cannot return a value. The destructor has the same name as of the class, except that the name is preceded by a ~ <em>(tilda)</em>.</p>
<h3>Composite Class</h3>
<p>A Composite object can be defined as one which consists of other objects.</p>
<p>As an example, consider the class <em>Circle</em> as composite object containing an instance of Point, representing the centre and radius which is of type, <em>float</em>. The definition of Point and Circle in this case would be.</p>
<div style="text-align:left;" dir="ltr">
<div>
<pre>class Point{
 float x;
 float y;
};

class Circle{
 float radius;
 Point centre;
};</pre>
</div>
</div>
<h3>Function Overloading</h3>
<p>In order to overload a function, a different signature should be used for each overloaded version. A function signature consists of the list of types of its arguments as well as their order. Here&#8217;s a set of valid overloaded versions of a function named f:</p>
<div style="text-align:left;" dir="ltr">
<div>
<pre>void f(char c, int i);
void f(int i, char c);
void f(string &amp; s);
void f();
void f(int i);
void f(char c);</pre>
</div>
</div>
<p>Note, however, that a function differing only by return type is illegal (it is legal to use different a return type with a different argument list, though) :</p>
<div style="text-align:left;" dir="ltr">
<div>
<pre>int f();  //error; differs from void f(); above only by return type
int f(float f);  //fine. unique signature</pre>
</div>
</div>
<p>You can overload the member functions in a class.</p>
<ul>
<li>Refer: <a title="http://publib.boulder.ibm.com/infocenter/macxhelp/v6v81/index.jsp?topic=/com.ibm.vacpp6m.doc/language/ref/clrc11cplr312.htm" rel="nofollow" href="http://publib.boulder.ibm.com/infocenter/macxhelp/v6v81/index.jsp?topic=/com.ibm.vacpp6m.doc/language/ref/clrc11cplr312.htm">http://publib.boulder.ibm.com/infocenter/macxhelp/v6v81/index.jsp?topic=/com.ibm.vacpp6m.doc/language/ref/clrc11cplr312.htm</a> Function Overloading</li>
<li>Refer for example: <a title="http://smart2help.com/e-books/ticpp-2nd-ed-vol-one/Chapter07.html" rel="nofollow" href="http://smart2help.com/e-books/ticpp-2nd-ed-vol-one/Chapter07.html">http://smart2help.com/e-books/ticpp-2nd-ed-vol-one/Chapter07.html</a></li>
</ul>
<h3>Operator Overloading</h3>
<p>When a class is defined, a set of operations are associated with it which together define the behavior of the instance of the class. So far, mnemonics have been used to name the operation. In some situations, it may be desirable to use operators which have conventional meaning rather than use a name for it. For example, consider the class IntSet, a set of integers class. To check if two instances are equal, one way is to define a member function</p>
<div style="text-align:left;" dir="ltr">
<div>
<pre>int IntSet::equal(IntSet &amp;s2);</pre>
</div>
</div>
<p>in the class IntSet, which could be used as follows:</p>
<div style="text-align:left;" dir="ltr">
<div>
<pre>if s1.equal(s2)</pre>
</div>
</div>
<p>Another way of doing this is to overload the C++ &#8220;==&#8221; operator in the class IntSet. The same functionalily can be coded as:</p>
<div style="text-align:left;" dir="ltr">
<div>
<pre>if (s1==s2)</pre>
</div>
</div>
<p>The C++ Operators which can be overloaded are arithmetic, logical, relational operators, as well as call(), subscripting[], dereferencing -&gt;, assignment =, the extraction &lt;&lt;&gt;&gt; operators.</p>
<ul>
<li>Refer: <a title="http://publib.boulder.ibm.com/infocenter/macxhelp/v6v81/index.jsp?topic=/com.ibm.vacpp6m.doc/language/ref/clrc11cplr318.htm" rel="nofollow" href="http://publib.boulder.ibm.com/infocenter/macxhelp/v6v81/index.jsp?topic=/com.ibm.vacpp6m.doc/language/ref/clrc11cplr318.htm">http://publib.boulder.ibm.com/infocenter/macxhelp/v6v81/index.jsp?topic=/com.ibm.vacpp6m.doc/language/ref/clrc11cplr318.htm</a> Operator Overloading</li>
<li>Refer for example: <a title="http://www.cplusplus.com/doc/tutorial/classes2/" rel="nofollow" href="http://www.cplusplus.com/doc/tutorial/classes2/">http://www.cplusplus.com/doc/tutorial/classes2/</a></li>
</ul>
<h3>The keyword this</h3>
<p>The keyword this represents a pointer to the object whose member function is being executed. It is a pointer to the object itself.</p>
<p>One of its uses can be to check if a parameter passed to a member function is the object itself.</p>
<h2>Problem Sets</h2>
<h3>Problem Set A</h3>
<p><strong>1. </strong> Define a class Random to provide random numbers within a range that is specified through the constructor. The class should provide a draw function to get a random number.</p>
<p>Use the code given below for the Random Class. <strong>You need to write the code in the given program wherever it is commented as write the code here</strong> o</p>
<div style="text-align:left;" dir="ltr">
<div>
<pre>#include //For I/O
#include     // For time()
#include   // For srand() and rand()

using namespace std;

class Random{
     private:
             int max;
             int min;
     public:
            Random(){
                 cout &lt;&lt; "Default Random Constructor is called and default values set with Min 10 and Max 20\n";
                    //Write the code here to set the default values for min 10 and max 20
            }
            Random(int minA, int maxA){
                 cout &lt;&lt; "Random Constructor called with argument of Min"&lt;&lt; minA &lt;&lt; " and Max"&lt;&lt;maxA&lt;&lt;"\n";
                   //Write the code here to set the max and min
            }
            int draw(){
                int r;
                srand(time(0));  // Initialize random number generator.
                r = (rand() % (max - min)) + min;
                return r;
            }
};

int main(void){
 //Write the code here to declare two Instances of Random class and by calling different constructors.

 //Use cout to call the draw function for each of the Random instance
}</pre>
</div>
</div>
<p>Refer: <a title="http://www.fredosaurus.com/notes-cpp/misc/random.html" rel="nofollow" href="http://www.fredosaurus.com/notes-cpp/misc/random.html">http://www.fredosaurus.com/notes-cpp/misc/random.html</a></p>
<pre>Name the program as: PA1_random.cpp
</pre>
<h3>Problem Set B</h3>
<p><strong>1. </strong>Write a class called Point that is capable of representing the coordinates of a point on a two-dimensional graph. You must permit creation of variables as follows:</p>
<p>Point p, q(2.1, -4.3);</p>
<p>The declaration of p above will be for the point (0,0).</p>
<p>Provide the following operations:</p>
<ol>
<li>Return the x coordinate or the y coordinate</li>
<li>Set the x coordinate or the y coordinate</li>
<li>Return the distance from the origin, formula is sqrt(x<sup>2</sup> + y<sup>2</sup>)</li>
<li>Input a point as two floating point numbers</li>
<li>Output a point in the format (2.1,-4.3)</li>
</ol>
<p>Write a short test main function for your class.</p>
<p>Refer: <a title="http://www.cppreference.com/wiki/c/math/start" rel="nofollow" href="http://www.cppreference.com/wiki/c/math/start">http://www.cppreference.com/wiki/c/math/start</a></p>
<pre>Name the program as PB1_Point.cpp
</pre>
<h3>Problem Set C</h3>
<p><strong>1. </strong>Write a class to hold the time of day. You must permit the creation of variables as follows:</p>
<p>Time t1, t2(3600), t3(12,00), t4(23, 59, 59);</p>
<p>In this case t1 is set to 00:00:00, t2 to 01:00:00 (3600 seconds), t3 to 12:00:00 and t4 to 23:59:59.</p>
<p>Provide the following operations:</p>
<ol>
<li>Return the hours, minutes or seconds</li>
<li>Return the total seconds using a cast operator overload to type long</li>
<li>Set the hours, minutes or seconds</li>
<li>Automatically convert an integer to a time, interpreting the integer value as the number of seconds</li>
<li>Input a time as three integers in the format hh:mm:ss</li>
<li>Output the time in the format hh:mm:ss</li>
<li>Add a specified number of seconds to a time</li>
<li>Overload the operator = for assignment and == for equality.</li>
</ol>
<p>Write a short test main function for your class.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/techonhand.wordpress.com/19/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/techonhand.wordpress.com/19/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/techonhand.wordpress.com/19/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/techonhand.wordpress.com/19/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/techonhand.wordpress.com/19/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/techonhand.wordpress.com/19/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/techonhand.wordpress.com/19/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/techonhand.wordpress.com/19/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/techonhand.wordpress.com/19/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/techonhand.wordpress.com/19/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/techonhand.wordpress.com/19/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/techonhand.wordpress.com/19/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/techonhand.wordpress.com/19/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/techonhand.wordpress.com/19/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=techonhand.wordpress.com&amp;blog=9884312&amp;post=19&amp;subd=techonhand&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://techonhand.wordpress.com/2009/10/11/creation-and-behavior-of-software-objects/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/a93e36381d7b6e452b246a24496e3884?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">seshhu143</media:title>
		</media:content>
	</item>
		<item>
		<title>Identifying Objects and Creating Software Objects</title>
		<link>http://techonhand.wordpress.com/2009/10/11/identifying-objects-and-creating-software-objects/</link>
		<comments>http://techonhand.wordpress.com/2009/10/11/identifying-objects-and-creating-software-objects/#comments</comments>
		<pubDate>Sun, 11 Oct 2009 10:56:39 +0000</pubDate>
		<dc:creator>seshhu143</dc:creator>
				<category><![CDATA[C ++]]></category>

		<guid isPermaLink="false">http://techonhand.wordpress.com/?p=14</guid>
		<description><![CDATA[Learning Objective Identifying Real world Objects Creating Software Objects using class. Implement state and behavior of software objects. Instructional Activities Reference Reading: What is an Object Object Oriented Programming CPlusPlus -&#62; Classes Basic tutorial Problem Sets Problem Set A 1. Identify 5 objects in real world List the state of these objects List the behavior [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=techonhand.wordpress.com&amp;blog=9884312&amp;post=14&amp;subd=techonhand&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<h2>Learning Objective</h2>
<ol>
<li>Identifying Real world Objects</li>
<li>Creating Software Objects using class.</li>
<li>Implement state and behavior of software objects.</li>
</ol>
<h2>Instructional Activities</h2>
<p>Reference Reading:</p>
<ul>
<li><a title="http://java.sun.com/docs/books/tutorial/java/concepts/object.html" rel="nofollow" href="http://java.sun.com/docs/books/tutorial/java/concepts/object.html">What is an Object</a></li>
<li><a title="http://en.wikipedia.org/wiki/Object-oriented_programming" rel="nofollow" href="http://en.wikipedia.org/wiki/Object-oriented_programming">Object Oriented Programming</a></li>
<li><a title="http://www.cplusplus.com/doc/tutorial/classes.html" rel="nofollow" href="http://www.cplusplus.com/doc/tutorial/classes.html">CPlusPlus -&gt; Classes Basic tutorial</a></li>
</ul>
<h2>Problem Sets</h2>
<p><a id="Problem_Set_A" name="Problem_Set_A"></a></p>
<h3>Problem Set A</h3>
<p><strong>1. </strong>Identify 5 objects in real world</p>
<ol>
<li>List the state of these objects</li>
<li>List the behavior of these objects</li>
<li>Note: Your list of objects should be unique from the entire class. Otherwise you would be give zero marks for the whole of this module</li>
</ol>
<p><a id="Problem_Set_B" name="Problem_Set_B"></a></p>
<h3>Problem Set B</h3>
<p><strong>1. </strong>Classes and Objects: Using the following class create an object for it in the main program</p>
<div style="text-align:left;" dir="ltr">
<div>
<pre>   class Integer {
     private:
         int integer;
     public:
         void readInteger();
         void printMessage();
  };

 void Integer::readInteger() {
      cout&lt;&lt;"enter the value of N";
       cin&gt;&gt;N;
 }
 void Integer::printMessage() {
              for (int i = 0 ; i &lt; N ; i++) {
                  cout&lt;&lt;Hello&lt;&lt;endl;
              }
  }</pre>
</div>
</div>
<ol>
<li> <strong>Create a object called “intobj”</strong> for the class “Integer” in the main program
<ul>
<li>Call intobj.readInteger() and intobj.printMessage() from the main program</li>
<li>Add another member function called int addInteger(int no) to the class Integer.</li>
<li>The function addInteger() returns the sum of the value of “N + no”.</li>
<li>Call intobj.addInteger() from the main program</li>
</ul>
</li>
<li> <strong>Create a class called &#8220;class Circle {  };&#8221; </strong>
<ul>
<li>Add members function to readRadius</li>
<li>Add a member function to displayArea</li>
<li>Create an object for the class Circle</li>
<li>Call the member functions readRadius() and displayArea() from the main program.</li>
</ul>
</li>
</ol>
<p><strong>2. </strong> Create the class called &#8216;Math&#8217;.</p>
<div style="text-align:left;" dir="ltr">
<div>
<pre>  class Math{
  private:
    int ival
  public:
     int sum(int x, int y);
 };</pre>
</div>
</div>
<ol>
<li> <strong>Create a class called “Math” </strong>
<ul>
<li>Complete the member function int sum(int x, int y);
<ul>
<li>return the sum of x and y;</li>
</ul>
</li>
<li>Write a main program which creates an object say “m” for the class “Math”
<ul>
<li>From the main program read two integers i1, i2.</li>
<li>Call the member function “total = m.sum(i1, i2)” to get the sum of i1 + i2</li>
</ul>
</li>
</ul>
</li>
<li> Accessing private member in member functions:
<ul>
<li>Modify the member functions so that sum() stores the output in ival.</li>
<li>ival = x + y;  return ival;</li>
</ul>
</li>
</ol>
<p><a id="Problem_Set_C" name="Problem_Set_C"></a></p>
<h3>Problem Set C</h3>
<p><strong>1. </strong>Create a class called State() with the following member functions</p>
<ul>
<li>readDistricts(); //read N = no of districts, dynamically allocated memory for N strings, read each district name from the stdin.</li>
<li>printDistricts();   //print the district names on the standard output (display-screen);</li>
<li>Use dynamic allocation of strings in the classes is compulsory:</li>
</ul>
<ol>
<li> Create an object for the class State in the main program</li>
<li> Call read_districts() and printDistricts() from the main program</li>
</ol>
<p><strong>2. </strong>Create class called Interest</p>
<ol>
<li> <strong>Create class called Interest</strong> with the following attributes and behavior
<ul>
<li>Attributes
<ul>
<li>Principle Amount</li>
<li>Number of Years</li>
<li>Rate of Interest</li>
</ul>
</li>
<li>Behavior
<ul>
<li>readPrincipleAmount();</li>
<li>readNoOfYears();</li>
<li>readInterestRatePY();</li>
<li>calcuateSimpleInterest();</li>
<li>calculateCompoundInterest();</li>
</ul>
</li>
</ul>
</li>
<li> Create an object for the class Interest in the main program</li>
<li> call member functions, read* to read principle amount, no. of years and interest rate</li>
<li> call calcuateSimpleInterest() and calculateCompoundInterest() to display the amount+interest separately.</li>
</ol>
<p><strong>3. </strong>Create class for 3 Objects identified in Problem Set A 1</p>
<p>Create 3 classes with state and behavior identified.</p>
<p>Create an object for the 3 classes in the main program and test them.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/techonhand.wordpress.com/14/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/techonhand.wordpress.com/14/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/techonhand.wordpress.com/14/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/techonhand.wordpress.com/14/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/techonhand.wordpress.com/14/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/techonhand.wordpress.com/14/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/techonhand.wordpress.com/14/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/techonhand.wordpress.com/14/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/techonhand.wordpress.com/14/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/techonhand.wordpress.com/14/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/techonhand.wordpress.com/14/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/techonhand.wordpress.com/14/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/techonhand.wordpress.com/14/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/techonhand.wordpress.com/14/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=techonhand.wordpress.com&amp;blog=9884312&amp;post=14&amp;subd=techonhand&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://techonhand.wordpress.com/2009/10/11/identifying-objects-and-creating-software-objects/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/a93e36381d7b6e452b246a24496e3884?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">seshhu143</media:title>
		</media:content>
	</item>
		<item>
		<title>Introduction to C++ and differences between C</title>
		<link>http://techonhand.wordpress.com/2009/10/11/introduction-to-c-and-differences-between-c/</link>
		<comments>http://techonhand.wordpress.com/2009/10/11/introduction-to-c-and-differences-between-c/#comments</comments>
		<pubDate>Sun, 11 Oct 2009 10:41:49 +0000</pubDate>
		<dc:creator>seshhu143</dc:creator>
				<category><![CDATA[C ++]]></category>

		<guid isPermaLink="false">http://techonhand.wordpress.com/?p=8</guid>
		<description><![CDATA[Learning Objective To know differences between C and C++ Demonstrate the capability of programming in C++ Apply C++ syntax, New/Delete and Reference operations Introduction Origins of C++ Stroustrup began work on C with Classes in 1979. The idea of creating a new language originated from Stroustrup&#8217;s experience in programming for his Ph.D. thesis. Stroustrup found [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=techonhand.wordpress.com&amp;blog=9884312&amp;post=8&amp;subd=techonhand&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<h2>Learning Objective</h2>
<ul>
<li>To know differences between C  and C++</li>
<li>Demonstrate the capability of programming in C++</li>
<li>Apply C++ syntax, New/Delete and Reference operations</li>
</ul>
<p><a id="Introduction" name="Introduction"></a></p>
<h2>Introduction</h2>
<p><strong>Origins of C++</strong></p>
<p>Stroustrup began work on C with Classes in 1979. The idea of creating a new language originated from Stroustrup&#8217;s experience in programming for his Ph.D. thesis. Stroustrup found that Simula (another programming language) had features that were very helpful for large software development, but the language was too slow for practical use.</p>
<p>Stroustrup set out to enhance the C language with Simula-like features. C was chosen because it is general-purpose, fast, and portable.</p>
<p><strong>The name C++&#8221;&#8216;</strong></p>
<p>This name is credited to Rick Mascitti (mid-1983) and was first used in December 1983. Earlier, during the research period, the developing language had been referred to as &#8220;new C&#8221;, then &#8220;C with Classes&#8221;.</p>
<p><strong>Features of C++</strong></p>
<p>Compared to the C language, C++ introduced extra features, including declarations as statements, function-like casts, new/delete, bool, reference types, inline functions, default arguments, function and operator overloading, namespaces and the scope resolution (::) operator, classes (including all class-related features such as inheritance, member functions, virtual functions, abstract classes, and constructors), templates, exception handling, runtime type identification, and the overloaded input (&gt;&gt;) and output (&lt;&lt;) operators for input and output respectively.</p>
<p>For more information <a title="http://en.wikipedia.org/wiki/C%2B%2B" rel="nofollow" href="http://en.wikipedia.org/wiki/C%2B%2B">Read</a></p>
<p><strong>Differences between C and C++</strong></p>
<p>The main difference between C and C++ is that C is a procedure oriented language where as C++ is an object oriented language we can compile and and execute all our c programs in a C++ compiler, c++ is an extension to c. C++ was first called &#8216;C with classes&#8217; the ++ in C++ indicates the increment operator in C meaning C++ is an advanced language compared to C. The advantage of C++ lies in object oriented programing generally called oops. The features of OOPS are classes, data abstraction, encapsulation, inheritance, polymorphism, exception handling,etc.,</p>
<p><a id="Resources" name="Resources"></a></p>
<h2>Resources</h2>
<ul>
<li><a title="Basic Input and Output" href="http://xoax.net/comp/cpp/console/Lesson2.php">XoaX.net Lesson 2 Basic Input and Output</a></li>
<li><a title="Namespace Essentials" rel="nofollow" href="http://xoax.net/comp/cpp/console/Lesson15.php">XoaX.net Lesson 15 Namespace Essentials</a></li>
<li><a title="DataTypes" rel="nofollow" href="http://xoax.net/comp/cpp/console/Lesson24.php">XoaX.net Lesson 24 Fundamental Data Types</a></li>
</ul>
<p><a id="Problem_Sets" name="Problem_Sets"></a></p>
<h2>Problem Sets</h2>
<p><a id="Problem_Set_A" name="Problem_Set_A"></a></p>
<h3>Problem Set A</h3>
<p><strong>1.</strong> Write a simple ‘Hello, new world!’ program in C and CPP edited, compiled and running on your chosen development platform. Change the program to take a command line argument (or multiple command line arguments) and to say ‘Hello name!’</p>
<pre>Solutions: PA1_HelloWorld.c and PA1_HelloWorld.cpp
</pre>
<p><strong>2.</strong> Tabulate all the basic C/C++ types, eg. Char, int, float, double. Don’t forget the unsigned, signed, short, long etc. Write a simple C and C++ program to print out the sizes in bytes of each type on your system.</p>
<pre>Solutions: PA2_BasicTypes.c and PA2_BasicTypes.cpp
</pre>
<p><strong>3.</strong> Find out on your system what the largest and smallest values are for the basic types above? Write a program in C and C++ to print out the Limits of each data type described in previous program.</p>
<pre>Solutions:PA3_limits.c and PA3_limits.cpp
</pre>
<p><a id="Problem_Set_B" name="Problem_Set_B"></a></p>
<h3>Problem Set B</h3>
<p><strong>1.</strong> Write a function to print the date, for the structure <strong>Date</strong> in C and C++.</p>
<p>You need to write the code wherever necessary for the given program in C and C++.</p>
<p><strong>Program to print date in C</strong></p>
<p>include &lt;stdio.h&gt; //Standard Input and Output Library</p>
<p>struct DATE</p>
<p>{</p>
<pre>int day;
int month;
int year;
</pre>
<p>};</p>
<p>void showDate(struct DATE d);</p>
<p>void setDate(int d, int m, int year, struct DATE * date);</p>
<p>int main(void)</p>
<p>{</p>
<pre>struct DATE date;
setDate(24,8,2009,&amp;date);
showDate(date);
return 1;
</pre>
<p>}</p>
<p>void showDate(struct DATE d)</p>
<p>{</p>
<pre>//Write your code here
</pre>
<p>}</p>
<p>void setDate(int d, int m, int y, struct DATE * date)</p>
<p>{</p>
<pre>//Write your code here
</pre>
<p>} &lt;/source&gt;</p>
<p><strong>Program to print date in C++</strong></p>
<p>include&lt;iostream&gt;  //Input/Output stream Library</p>
<p>using namespace std;</p>
<p>struct Date</p>
<p>{</p>
<pre>int day;
int month;
int year;
void showDate()
{
 //Write your code here
</pre>
<pre>}
void setDate(int d, int m, int y){
 //Write your code here
}
</pre>
<p>};</p>
<p>int main(void)</p>
<p>{</p>
<pre>struct Date date;
date.setDate(24,8,2009);
date.showDate();
system("PAUSE");
return 1;
</pre>
<p>}</p>
<p>Resources:</p>
<ul>
<li><a title="http://www.cs.uregina.ca/Links/class-info/cplusplus/Structure.html" rel="nofollow" href="http://www.cs.uregina.ca/Links/class-info/cplusplus/Structure.html">http://www.cs.uregina.ca/Links/class-info/cplusplus/Structure.html</a></li>
</ul>
<pre>Solutions: PB1_print_date.c and PB1_print_date.cpp
</pre>
<p><strong>2.</strong> Write the struct Date(of previous program) in separate namespace in C++ and use the Date structure in main to print the date.</p>
<pre>Solutions: PB2_ns_print_date.cpp
</pre>
<p><a id="Problem_Set_C" name="Problem_Set_C"></a></p>
<h3>Problem Set C</h3>
<p><strong>Write the code in C++ for all the problems given in this problem set.</strong></p>
<p><strong>1.</strong> STDIO: Read an integer value N from standard input.</p>
<ul>
<li>Print “MSIT @ IIIT Hyderabad and JNTU Hyderabad” for N times using a for-loop.</li>
</ul>
<p>Resources:</p>
<ul>
<li><a title="http://www.cplusplus.com/doc/tutorial/program_structure.html" rel="nofollow" href="http://www.cplusplus.com/doc/tutorial/program_structure.html">http://www.cplusplus.com/doc/tutorial/program_structure.html</a></li>
<li><a title="http://www.cplusplus.com/doc/tutorial/basic_io.html" rel="nofollow" href="http://www.cplusplus.com/doc/tutorial/basic_io.html">http://www.cplusplus.com/doc/tutorial/basic_io.html</a></li>
<li><a title="http://www.cplusplus.com/doc/tutorial/control.html" rel="nofollow" href="http://www.cplusplus.com/doc/tutorial/control.html">http://www.cplusplus.com/doc/tutorial/control.html</a></li>
</ul>
<pre>Solutions: PC1_cout_n.cpp
</pre>
<p><strong>2.</strong> STRINGS: use “string” variable</p>
<ul>
<li>Read your firstName</li>
<li>Read your lastName</li>
<li>Use “+” string operator and contenate firstName and lastName with “_” in between.</li>
<li>Display firstName_lastName on the screen</li>
<li>Use length() function of string class and display the length of “firstName_lastName”</li>
<li>Access the characters in the string “firstName_lastName” and display one by one separated by a single space</li>
<li>Ex: Display “Kishore_Prahallad” as “K i s h o r e _ P r a h a l l a d”</li>
<li>Display the characters in reverse order</li>
<li>Display as “d a l l a h a r P _ e r o h s i K”</li>
</ul>
<p>Resources</p>
<ul>
<li><a title="http://www.yolinux.com/TUTORIALS/LinuxTutorialC++StringClass.html" rel="nofollow" href="http://www.yolinux.com/TUTORIALS/LinuxTutorialC++StringClass.html">http://www.yolinux.com/TUTORIALS LinuxTutorialC++StringClass.html</a></li>
<li><a title="http://www.cppreference.com/wiki/string/start" rel="nofollow" href="http://www.cppreference.com/wiki/string/start">http://www.cppreference.com/wiki/string/start</a></li>
</ul>
<pre>Solutions: PC2_string.cpp
</pre>
<p><strong>3.</strong> Using new and delete in C++</p>
<ol>
<li>New and Delete for integer:</li>
</ol>
<ul>
<li>Read an integer N</li>
<li>Create a 1-dimensional dynamic integer array using new[] for N integers</li>
<li>Read N integers from the standard input</li>
<li>Delete the allocated memory using delete[]</li>
</ul>
<ol>
<li>New and Delete for Strings:</li>
</ol>
<ul>
<li>Read an integer N</li>
<li>Create a 1-dimensional dynamic string array using new[] for N strings</li>
<li>Read N strings from the standard input</li>
<li>Delete the allocated memory using delete[]</li>
</ul>
<ol>
<li>New and Delete for 2-dimensional Matrix:</li>
</ol>
<ul>
<li>Read two integers N and M</li>
<li>Create a 2-dimensional dynamic integer array using new[]</li>
<li>Read N x M integers from standard input</li>
<li>Delete using delete[]</li>
</ul>
<p>Use separate functions for integer, strings and 2D Matrix.</p>
<p>Resources:</p>
<ul>
<li><a title="http://www.cplusplus.com/doc/tutorial/dynamic.html" rel="nofollow" href="http://www.cplusplus.com/doc/tutorial/dynamic.html">http://www.cplusplus.com/doc/tutorial/dynamic.html</a></li>
</ul>
<pre>Solutions: PC3_new_delete.cpp
</pre>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/techonhand.wordpress.com/8/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/techonhand.wordpress.com/8/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/techonhand.wordpress.com/8/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/techonhand.wordpress.com/8/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/techonhand.wordpress.com/8/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/techonhand.wordpress.com/8/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/techonhand.wordpress.com/8/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/techonhand.wordpress.com/8/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/techonhand.wordpress.com/8/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/techonhand.wordpress.com/8/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/techonhand.wordpress.com/8/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/techonhand.wordpress.com/8/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/techonhand.wordpress.com/8/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/techonhand.wordpress.com/8/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=techonhand.wordpress.com&amp;blog=9884312&amp;post=8&amp;subd=techonhand&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://techonhand.wordpress.com/2009/10/11/introduction-to-c-and-differences-between-c/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/a93e36381d7b6e452b246a24496e3884?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">seshhu143</media:title>
		</media:content>
	</item>
	</channel>
</rss>
