<?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/"
	>

<channel>
	<title>Interview Mantra &#187; functions</title>
	<atom:link href="http://www.interviewmantra.net/tag/functions/feed" rel="self" type="application/rss+xml" />
	<link>http://www.interviewmantra.net</link>
	<description>Your mantra to job success</description>
	<lastBuildDate>Mon, 06 Feb 2012 11:10:20 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.2.1</generator>
		<item>
		<title>C++ Medium Interview Questions – part2</title>
		<link>http://www.interviewmantra.net/2010/01/cpp-medium-interview-questions-part2.html</link>
		<comments>http://www.interviewmantra.net/2010/01/cpp-medium-interview-questions-part2.html#comments</comments>
		<pubDate>Mon, 11 Jan 2010 02:00:38 +0000</pubDate>
		<dc:creator>Saurabh Manchanda</dc:creator>
				<category><![CDATA[C++]]></category>
		<category><![CDATA[Interview Questions]]></category>
		<category><![CDATA[c++ interview questions]]></category>
		<category><![CDATA[c++ template]]></category>
		<category><![CDATA[classes]]></category>
		<category><![CDATA[cpp interview questions]]></category>
		<category><![CDATA[functions]]></category>
		<category><![CDATA[medium difficulty]]></category>
		<category><![CDATA[operators]]></category>
		<category><![CDATA[typecasting]]></category>

		<guid isPermaLink="false">http://www.interviewmantra.net/?p=529</guid>
		<description><![CDATA[This post is a part of an ongoing series of C++ Interview Questions. This is Second part of the two parts of C++ interview questions with medium difficulty. These questions were handpicked by the author, who happens to be an active member in one of the largest C++ communities in Orkut which boasts to have [...]]]></description>
			<content:encoded><![CDATA[<p></p><p>This post is a part of an ongoing series of <a href="http://www.interviewmantra.net/category/interview-questions/cpp">C++ Interview Questions</a>. This is Second part of the two parts of C++ interview questions with <strong>medium</strong> difficulty.</p>
<p>These questions were handpicked by the author, who happens to be an active member in one of the largest C++ communities in Orkut which boasts to have over 146,000 members.</p>
<h3>6. What are pure virtual functions? Give a real-world example for abstract class and pure virtual function?</h3>
<p>A pure virtual function is a virtual function that doesn&#8217;t require a definition in the base class. <span id="more-529"></span>A pure virtual function is defined by writing =0 after its signature. The definition can be provided if some default behavior or error-handling is required.</p>
<p>In some cases it&#8217;s not logical to instantiate an object of a class. In such cases, the concept of abstract classes can be made use of. To make a class abstract, the class needs to include at least one pure virtual function.</p>
<p><strong> For Example:</strong></p>
<p>Consider a class Employee that defines the generic behavior of different types of Employees that work in a company.</p>
<pre class="brush: cpp; title: ; notranslate">
#include&lt;iostream&gt;
#include&lt;string&gt;

using std::string;

class Employee
{
      string name;
      string Emp_num;

protected:
      int Basic;
      float allowance;

public:
      Employee(string _name, string _num, int _base, float allow): name(_name), Emp_num(_num), Basic(_base), allowance(allow){}

      virtual ~Employee(){}

      virtual float salary()=0;
      int getBasic(){ return Basic; }
      std::string getName(){ return name; }
};

class Manager: public Employee
{

public:
      Manager(string name, string Emp_num, int Base): Employee(name, Emp_num, Base, 3.2){}

      Manager(string name, string Emp_num, int Base, float allow): Employee(name, Emp_num, Base, allow){}

      float salary()
      {
            float sal;

            /*Calculations for Manager's salary*/
            sal = Basic + (allowance/100)*Basic;
            return sal;
      }
};

class Executive: public Employee
{

public:
      Executive(string name, string Emp_num, int Base): Employee(name, Emp_num, Base, 1.2){}

      Executive(string name, string Emp_num, int Base, float allow): Employee(name, Emp_num, Base,allow){}

      float salary()
      {
            float sal;

            /*Calculations for Executive's salary*/
            sal = Basic + (allowance/100)*Basic;
            return sal;
      }
};

int main()
{
      Employee *Mgr= new Manager(&quot;Saurabh&quot;,&quot;M001&quot;, 50000);
      Employee *Exec = new Executive(&quot;Ajay&quot;,&quot;E002&quot;, 20000);

      std::cout&lt;&lt;&quot;Manager's salaryt: &quot;&lt;&lt;Mgr-&gt;salary();
      std::cout&lt;&lt;&quot;nExecutive's salaryt: &quot;&lt;&lt;Exec-&gt;salary();
}
</pre>
<p>Here, the Employee has been made an abstract class because every Employee needs to be one of Manager, Executive, Trainee, etc.. The existence of an Employee in itself doesn&#8217;t tell you where the Employee stands in the hierarchy.</p>
<h3>7. What is a template?</h3>
<p>Templates in C++, are a way to achieve generic nature in programming. By using templates, we can define functions and classes that show the same( or similar) behavior on different types.</p>
<p><strong> For Example:</strong></p>
<pre class="brush: cpp; title: ; notranslate">
#include&lt;iostream&gt;

template&lt;typename T&gt;
void swap(T&amp;amp;amp; obj1, T&amp;amp;amp; obj2)
{
      T temp = obj1;
      obj1 = obj2;
      obj2 = temp;
}

int main()
{
      int val1=20, val2=50;
      std::cout&lt;&lt;&quot;Before Swap:t&quot;;
      std::cout&lt;&lt;&quot;val1 = &quot;&lt;&lt;val1&lt;&lt;&quot; val2 = &quot;&lt;&lt;val2&lt;&lt;std::endl;
      swap(val1, val2);
      std::cout&lt;&lt;&quot;After Swap:t&quot;;
      std::cout&lt;&lt;&quot;val1 = &quot;&lt;&lt;val1&lt;&lt;&quot; val2 = &quot;&lt;&lt;val2&lt;&lt;std::endl;
}
</pre>
<p><strong>Note</strong>: Don&#8217;t use this swap(T&amp;,T&amp;) to swap container objects, because copying and assignment may cause heavy overheads. Instead, use the swap() function provided by the container itself.</p>
<p><strong> For Example:</strong></p>
<pre class="brush: cpp; title: ; notranslate">
template&lt;typename T&gt;
class List
{
      struct Link{ T data; Link* next;};
      Link head;
public:
      void insert(T data) { /*Add new node*/ }
      void remove()       { /*Remove a node*/ }
      T fetch()             { /*Return first node data*/ }
};
</pre>
<p>Now, one can have a List of ints, List of chars, List of strings, etc..</p>
<h3>8. What is the conversion operator?</h3>
<p>The conversion operator is used to convert a user-defined type to some other type.</p>
<p>Consider a class smallInt that is used to store integers in range [0,5000]. Objects of such type would be constantly exposed to arithmetic operations.</p>
<p>To access the integer value of the object, we can</p>
<ol>
<li>use accessor methods</li>
<li>use conversion operator</li>
</ol>
<p>Using an accessor method again and again in an expression would invoke unnecessary invitations to explicit function calls and the code would become procedure-oriented rather than data-oriented.</p>
<p>Instead we can define a conversion operator that will fetch the integer value wrapped in the smallInt object whenever required.</p>
<pre class="brush: cpp; title: ; notranslate">
#include&lt;iostream&gt;
#include&lt;stdexcept&gt;

class smallInt
{
      int value;
public:
      smallInt(): value(0){}

      smallInt(int x): value(x)
      {
            if(x&gt;5000 || x&lt;0)
                  throw std::out_of_range(&quot;smallInt Range: 0-5000&quot;);
      }

      operator int(){ return value;}
};

int main()
{
    try{
        smallInt obj500(500), obj33(33);
        std::cout&lt;&lt;obj500*obj33;
        smallInt object = obj500*obj33;        //throws exception
    }catch(std::out_of_range&amp;amp;amp; e){std::cout&lt;&lt;&quot;n&quot;&lt;&lt;e.what();}
}
</pre>
<p><strong>PS:</strong> out_of_range can be accessed using the  header stdexcept</p>
<h3>9. What are the different casts supported by C++?</h3>
<p>C++ supports a variety of casts. They can be listed as :</p>
<ol>
<li><strong>C-style cast</strong><br />
float myFloat=24.829;<br />
int myInt = (int)myFloat;</li>
<li><strong>Function-style cast</strong><br />
int myInt = int(myFloat);</p>
<p>The above two casts are not reliable and should be used to cast between built-in types only.</li>
<li><strong>static_cast &lt; T &gt; (f)</strong><br />
These are less dangerous than the C-style casts. Should be used when an implicit conversion from T to F or  vice-versa exists. This can be used to cast numeric types or for upcasting class objects.<br />
Also, these can be used to convert a base-class pointer to a derived-class pointer, but as it is done during compile-time, the dynamic type is not known. Hence this cast can invite trouble.</p>
<p><strong>Example 1:</strong></p>
<pre class="brush: cpp; title: ; notranslate">
class base
{
      /*Members*/
};

class derived: public base
{
      /*Members*/
};

base* ptr_bb = new base;
base* ptr_bd = new derived;

/*Conversion 1*/
derived* ptr_db = static_cast&lt;derived*&gt;(ptr_bb);

/*Conversion 2*/
derived* ptr_dd = static_cast&lt;derived*&gt;(ptr_bd);
</pre>
<p>This would compile fine but during run-time it might cause problems because in Conversion 1, ptr_bb points to an object of its Base-type and not to its derived.<br />
Conversion 2 is safe because ptr_bd points to a derived object which can be well-handled using ptr_dd which is a pointer to derived type.</p>
<p><strong>Example 2:</strong></p>
<p>float myFloat = 24.222;<br />
int myInt = static_cast(myFloat);</li>
<li><strong>dynamic_cast &lt; T &gt;(f)</strong><br />
This cast is type-safe in nature. It&#8217;s used to downcast pointers and references to their base class safely. This cast is done at run-time and returns the correct sub-object if the cast was possible, else returns 0 and throws a bad_cast exception. It is required that there be at least one virtual function in the base class.</p>
<p><strong>For Example:</strong>
<pre class="brush: cpp; title: ; notranslate">
base* ptr_b1 = new base;
base* ptr_b2 = new derived;

/* Conversion 1. ptr_d1 will be zero*/
derived* ptr_d1 = dynamic_cast&lt;derived*&gt; ptr_b1;

/* Conversion 2. ptr_d2 will be valid*/
derived* ptr_d2 = dynamic_cast&lt;derived*&gt; ptr_b2;
</pre>
</li>
<li><strong>reinterpret_cast &lt; T &gt;(f)</strong><br />
This type of cast is a very rarely used cast, because the after-effect is implementation-defined,i.e., . It treats the pointers and references as incomplete types. The casted value obtained should be used only after casting back to its original type.</li>
<li><strong>const_cast &lt; T &gt;(f)</strong><br />
This cast is used to cast away the const-ness of objects or pointers. This should be used only when one is sure that the underlying object was not defined to be a const. If the underlying object was a const, it would invoke Undefined Behavior.</li>
</ol>
<h3>10. What is the auto_ptr? Why is it required?</h3>
<p>The auto_ptr is a type declared in the &lt;memory&gt; header. It is used to get the basic Resource Acquisition is Initialization(RAII) features.</p>
<p>The RAII features are required to write an exception-free code. This is because if a function throws an exception, then stack unwinding takes place and it destroys the objects on the stack, but not those that are allocated dynamically.</p>
<p>Hence, we can create a type that will wrap the pointer and use accessor functions to access the memory. As the object would be on the stack, its destructor would be called during the stack unwinding and hence, the dynamically allocated memory is freed.</p>
<p><strong> For Example:</strong></p>
<pre class="brush: cpp; title: ; notranslate">
#include&lt;iostream&gt;
#include&lt;memory&gt;

int main()
{
    std::auto_ptr&lt;int&gt; x(new int);
    std::cin&gt;&gt;*x;
    std::cout&lt;&lt;*x;
}
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.interviewmantra.net/2010/01/cpp-medium-interview-questions-part2.html/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>C++ Medium Interview Questions – part1</title>
		<link>http://www.interviewmantra.net/2009/12/cpp-medium-interview-questions-part1.html</link>
		<comments>http://www.interviewmantra.net/2009/12/cpp-medium-interview-questions-part1.html#comments</comments>
		<pubDate>Sun, 20 Dec 2009 02:00:28 +0000</pubDate>
		<dc:creator>Saurabh Manchanda</dc:creator>
				<category><![CDATA[C++]]></category>
		<category><![CDATA[Interview Questions]]></category>
		<category><![CDATA[c++ interview questions]]></category>
		<category><![CDATA[container classes]]></category>
		<category><![CDATA[cpp interview questions]]></category>
		<category><![CDATA[destructor]]></category>
		<category><![CDATA[functions]]></category>
		<category><![CDATA[medium difficulty]]></category>
		<category><![CDATA[operator overloading]]></category>

		<guid isPermaLink="false">http://www.interviewmantra.net/?p=510</guid>
		<description><![CDATA[This post is a part of an ongoing series of C++ Interview Questions. This is First part of the two parts of C++ interview questions. Each part consists of 5 questions along with detailed answers. What’s common in all the questions in this set is that the level of difficulty is Medium. Read Part2 of [...]]]></description>
			<content:encoded><![CDATA[<p></p><p>This post is a part of an ongoing series of <a href="http://www.interviewmantra.net/category/interview-questions/cpp">C++ Interview Questions</a>. This is First part of the two parts of C++ interview questions. Each part consists of 5 questions along with detailed answers. What’s common in all the questions in this set is that the level of difficulty is <strong>Medium</strong>.</p>
<h3>Read <a href="http://www.interviewmantra.net/2010/01/cpp-medium-interview-questions-part2.html">Part2 of C++ Medium Interview Questions</a></h3>
<p>These questions were handpicked by the author, who happens to be an active member in one of the largest C++ communities in Orkut which boasts to have over 146,000 members.</p>
<h3>1. What are the POD types?</h3>
<p>In C++, a POD or a Plain-Old Data type is either a scalar type or a POD class.</p>
<p>Scalar types are those that represent a single value. The int, float, bool, etc are scalar types.<span id="more-510"></span></p>
<p>A POD class is one which has no user-defined constructor, no user-defined assignment operator and no non-static member which in itself is non-POD. It should have only public members, no base classes and no virtual functions.</p>
<h3>2. What are the container classes supported by C++ ?</h3>
<p>C++ supports a number of container classes, divided into 3 categories:</p>
<ol>
<li>Sequence Containers:<br />
vector, deque and list.</li>
<li>Associative Containers:<br />
map, multimap, set, multiset and bitset</li>
<li>Adapters:<br />
stack, queue and priority_queue</li>
</ol>
<h3>3. What is the difference between delete and destructor in C++?</h3>
<p>The delete operator is responsible for freeing the dynamically allocated memory while the destructor is responsible for cleaning up an object just before the memory is actually freed.</p>
<p>The delete operator is used on a pointer to free the memory dynamically allocated by the pointer. It is required to be called explicitly by the program, else there would be memory leaks. delete-ing an object leads to invocation of the destructor.</p>
<p>A destructor is invoked implicitly, when the scope of an object ends or when the dynamically allocated object is deleted, in all cases except when the allocation is done using <strong>placement new</strong>. The destructor performs the functions just opposite to the constructor. It is used to clean up the resources, before the object goes out of scope or the memory is de-allocated.</p>
<p><strong> For Example:</strong></p>
<pre class="brush: cpp; title: ; notranslate">
#include&lt;iostream&gt;

class dummy
{
      int a;
public:
      dummy(): a(0)
      { std::cout&lt;&lt;&quot;Default constructor\n&quot;; }

      dummy(int x): a(x)
      { std::cout&lt;&lt;&quot;Parametrized constructor\n&quot;;}

      ~dummy()
      { std::cout&lt;&lt;&quot;Destructor\n&quot;;}
};

int main()
{

/*Allocates memory dynamically and then calls constructor*/
      dummy* ptr = new dummy;

/*New Block starts */
      {

/* Allocates memory on the stack and then calls constructor */
            dummy myObj(25);

      }
/*myObj out of scope. Destructor called*/

/*Object pointed by ptr is deleted and destructor called*/
    delete ptr;
}
</pre>
<p>If the statement &#8220;delete ptr;&#8221; is removed, the destructor for the object won&#8217;t be called and the memory would not be freed.</p>
<h3>4. What is function overloading and operator overloading?</h3>
<p>Overloading is a method of implementing Polymorphism in C++.</p>
<p>Function overloading is one where different functions with the same name are defined and which function is called depends upon the data type being passed.</p>
<p><strong> For Example:</strong><br />
One may want functions to add different types of data.</p>
<pre class="brush: cpp; title: ; notranslate">
int add(int a, int b){return a+b;}

double  add(double a, double b){ return a+b;}
</pre>
<p>Now a call, say add(4, 5) would invoke the add function taking two int arguments.</p>
<p>Operator overloading is a way to make the built-in operators work on the User-defined types. This makes the user-defined types to look like the built-in types and thus makes the code generic and realistic.</p>
<p><strong> For Example:</strong><br />
A class Time can overload the + operator to add minutes and &#8211; operator to subtract minutes.</p>
<pre class="brush: cpp; title: ; notranslate">
#include&lt;iostream&gt;

class Time{

      int hrs, min, sec;
public:
      Time()    {/*Assign System Time */}
      Time(int inHrs, int inMin=0, int inSec=0): hrs(inHrs), min(inMin), sec(inSec){}

      Time&amp; operator+(int minutes)
      {addMinutes(minutes); return *this;}

      Time&amp; operator-(int minutes)
      {subMinutes(minutes); return *this;}

      void addMinutes(int minutes) {/*Add Minutes*/}
      void addSeconds(int seconds) {/*Add seconds*/}
      void addHours(int hours) {/*Add hours*/}

      void subMinutes(int minutes) {/*Subtract Minutes*/}
      void subSeconds(int seconds) {/*Subtract seconds*/}
      void subHours(int hours) {/*Subtract hours*/}
};

int main()
{
      Time t1(12,20,13);        /* t1 has 12:20:13 */
      Time t2 = t1 + 50;        /* t2 has 13:10:13 */
}
</pre>
<h3>5. What are virtual functions?</h3>
<p>A virtual function in C++ can be used inside a class to implement dynamic polymorphism by overriding the methods of its direct or indirect base class.</p>
<p>It is used when the base class function can&#8217;t completely define the behavior of the object and hence, the control is handed over to the correct function which can handle it whenever possible. The calls to the correct function are bound during run-time.</p>
<p><strong>For example:</strong><br />
Consider a class &#8216;Shape&#8217; that represents geometric shape. Let Polygon and Circle inherit from this Shape class. Let there be two possible behaviors of Polygon and Circle, draw() and area().</p>
<p>The Shape class can&#8217;t define the functions, because both depend on the type of the Shape. The area of a circle is different from the area of a square. Hence, these functions are made virtual.</p>
<pre class="brush: cpp; title: ; notranslate">
#include &lt;iostream&gt;
const float PI = 3.14;

class Shape
{
      public:
          virtual float area() { return -1;};

//Other functions
};

class Square: public Shape
{
      float edge;
public:
      Square(float side): edge(side){ }
      float area(){ return edge*edge; }

      //Other functions
};

class Circle: public Shape
{
      float radius;
public:
      Circle(float R) : radius(R) { }
      float area() { return PI * radius * radius; }

//Other functions
};

int main()
{
      Shape* myShape = new Circle(29);

      /* This will return Circle's area*/
      std::cout &lt;&lt; &quot;Area : &quot; &lt;&lt; myShape-&gt;area();
      delete myShape;

      /*Creates a Square with Side = 10 units*/
      myShape = new Square(10);

      /* This will return Square's area */
      std::cout &lt;&lt; &quot;Area : &quot; &lt;&lt; myShape-&gt;area();
      delete myShape;
}
</pre>
<p><strong>Note</strong>: It would be a good design practice to make the Shape class abstract because a Shape in itself doesn&#8217;t make sense.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.interviewmantra.net/2009/12/cpp-medium-interview-questions-part1.html/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>

<!-- Performance optimized by W3 Total Cache. Learn more: http://www.w3-edge.com/wordpress-plugins/

Minified using disk: basic
Page Caching using disk: enhanced

Served from: www.interviewmantra.net @ 2012-02-09 11:35:22 -->
