<?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; C++</title>
	<atom:link href="http://www.interviewmantra.net/category/interview-questions/cpp/feed" rel="self" type="application/rss+xml" />
	<link>http://www.interviewmantra.net</link>
	<description>Your mantra to job success</description>
	<lastBuildDate>Thu, 29 Jul 2010 06:38:25 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0</generator>
		<item>
		<title>Tata Technologies Looking for C/C++/Java programmers</title>
		<link>http://www.interviewmantra.net/2010/06/tata-technologies-c-cpp-java-programmers.html</link>
		<comments>http://www.interviewmantra.net/2010/06/tata-technologies-c-cpp-java-programmers.html#comments</comments>
		<pubDate>Fri, 04 Jun 2010 13:05:04 +0000</pubDate>
		<dc:creator>guest</dc:creator>
				<category><![CDATA[Announcements]]></category>
		<category><![CDATA[C]]></category>
		<category><![CDATA[C++]]></category>
		<category><![CDATA[IT]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Job Search]]></category>

		<guid isPermaLink="false">http://www.interviewmantra.net/?p=1285</guid>
		<description><![CDATA[Tata Technologies Ltd. is hiring 40 professionals for Pune Location.  Headquartered in Singapore,   Tata Technologies Limited is a leader in engineering services outsourcing with over 4,000 highly skilled employees. Do you meet the following criteria? If yes, send your resume asap to sridhar@interviewmantra.net Possess 2 to 5 years of IT Experience. Education &#8211; BE [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.tatatechnologies.com/">Tata Technologies Ltd.</a> is hiring 40 professionals for Pune Location.  Headquartered in Singapore,   Tata Technologies Limited is a leader in engineering services outsourcing with over  4,000 highly skilled employees.</p>
<p>Do you meet the following criteria? If yes, send your resume asap to <a href="mailto:sridhar@interviewmantra.net?subject=Job Application for Tata Technologies">sridhar@interviewmantra.net</a></p>
<ul>
<li>Possess 2 to 5 years of IT Experience.</li>
<li>Education &#8211; BE or MCA.</li>
<li>Programming experience  in <strong>C/C++/</strong><strong> Java</strong> (Swings, Servlets, JSP, strong OO skills).</li>
<li>Knowledge of Teamcenter  ITK programming is a huge advantage.</li>
<p><a href="mailto:sridhar@interviewmantra.net?subject=Job Application for Tata Technologies"><img title="Apply Job" src="http://www.interviewmantra.net/wp-content/uploads/2010/06/apply_now.jpg" alt="" width="50" height="50" /></a>
</ul>
<p><em>Note that this requirement is for Indian National only. </em></p>
]]></content:encoded>
			<wfw:commentRss>http://www.interviewmantra.net/2010/06/tata-technologies-c-cpp-java-programmers.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>C++ Hard Interview Questions – part2</title>
		<link>http://www.interviewmantra.net/2010/04/cpp-hard-interview-questions-part2.html</link>
		<comments>http://www.interviewmantra.net/2010/04/cpp-hard-interview-questions-part2.html#comments</comments>
		<pubDate>Wed, 14 Apr 2010 12:00:57 +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[cpp interview questions]]></category>
		<category><![CDATA[RAII]]></category>
		<category><![CDATA[RTTI]]></category>

		<guid isPermaLink="false">http://www.interviewmantra.net/?p=899</guid>
		<description><![CDATA[In websites such as coolinterview.com, geekinterview.com, you will find plethora of technical interview questions. But all the questions there are posted and answered by the users. You might have found that some questions mentioned there are of any use. Also you will most of the answers not much reliable. We at interviewmantra, extensively research for [...]]]></description>
			<content:encoded><![CDATA[<p>In websites such as <a href="http://www.coolinterview.com">coolinterview.com</a>, <a href="http://www.geekinterview.com">geekinterview.com</a>, you will find plethora of technical interview questions. But all the questions there are posted and answered by the users. You might have found that some questions mentioned there are of any use. Also you will most of the answers not much reliable. We at interviewmantra, extensively research for good interview questions, categorize them according to difficulty, answer each of them in detail, make sure that the answers are correct to the best of our knowledge. Here is the last 5 questions in <a href="http://www.interviewmantra.net/tag/c-interview-questions">this series of C++ interview questions</a>. Hope these are of use to you for interview preparation. </p>
<h3>6. What&#8217;s the knack with vector&lt;bool&gt;?</h3>
<p>The std::vector&lt;bool&gt; is a specialization of the std::vector&lt;&gt; class template, i.e., when an object of vector&lt;bool&gt; is created, it uses a specialized and highly optimized version of the vector&lt;&gt; template, instead of instantiating the template for the bool type. The vector&lt;bool&gt; stores boolean data as bits and not as bool variables (which could take a whole byte to store a single true or a false).</p>
<p>The vector&lt;bool&gt;  is optimized on space, rather than on speed, unlike the vector&lt;&gt; template. Moreover, this optimization has been forced upon the users because of the specialization. Also, the vector&lt;bool&gt; items are not addressable and the specialization defines the iterator in a form different than that of vector&lt;&gt; which is not random-access. For more info, check <a href="http://www.informit.com/guides/content.aspx?g=cplusplus&amp;seqNum=98" target="_blank">here</a></p>
<h3>7. What is the difference between assignment operator and a copy constructor?</h3>
<p>As the names suggest, the copy constructor is used to &#8220;construct an object&#8221;. The new object is an exact copy of another object that is already constructed. The assignment operator is used to &#8220;assign an object&#8221; with the value(s) of some other object. Hence, the assignment operator is something that comes into action when we have an object to the LHS of the &#8216;=&#8217; operator and some expression to the RHS.</p>
<p><strong>For Example:</strong><br />
For some type T and &#8220;params&#8221; for the object&#8217;s constructor,</p>
<pre class="brush: cpp;">{
   T x (params1, ...);
   T y (params2, ...);

   T z = x; /* Copy : z created with the value of x */
   y = x+z; /* Assignment : y gets the value equivalent to x+z */
}</pre>
<p>If a programmer doesn&#8217;t write a copy constructor or an assignment operator, then the compiler provides one. The copy constructor provided by the compiler does a <a href="http://www.interviewmantra.net/2010/02/cpp-hard-interview-questions-part1.html#copy" target="_blank">shallow-copy</a> of the objects and, hence, could lead to problems. And, when the programmer overloads the assignment operator for a particular class, s/he must take care of <a href="http://www.interviewmantra.net/2010/02/cpp-hard-interview-questions-part1.html#Self" target="_blank">self-assignment</a> and free the resources before the assignment is done.</p>
<h3>8. Why we would use exception handling rather than different return values to signal an error?</h3>
<p>The probability of a program failing is never zero and, when when such conditions arise, different steps shall be taken. Two options are &#8211; Returning an Error code and using Exception Handling.<br />
Returning an error-code is fine but has some problems associated with it:</p>
<ol>
<li>The error-code returned is generally of type &#8220;int&#8221;. The problem here is that if certain integer values are associated with error-codes, then the function would have to exclude those from the valid return values, which isn&#8217;t feasible in all situations.</li>
<li>Even if the above is feasible, the code would require code to check the return value for each call and this would cause code bloat.</li>
<li>Some error codes are used to signal that the system is in non-recoverable state and needs to exit. This might not be a good thing to be done at all times, for example, if the code that generates the error and terminates the program is part of a library and is being run as a part of a system that can&#8217;t be terminated.</li>
</ol>
<p>The above problems are not seen while using Exception handling because it separates the error-handling code from the program logic. This also makes the code clean and readable.</p>
<h3>9. What is RAII?</h3>
<p>Resource Acquisition Is Initialization or RAII is a design pattern that helps in creating objects, on the heap, that are safely destructed. The RAII technique requires a wrapper to be used to hold the resource so that when the wrapper object goes out of scope or an exception is thrown, the resource is freed.</p>
<p><strong>For Example:</strong></p>
<pre class="brush: cpp;">#include&lt;exception&gt;
#include&lt;iostream&gt;
#include&lt;string&gt;

struct someClass{};

class Wrap
{
   someClass* ptr;
public:
   Wrap() : ptr(0){}
   Wrap(someClass* obptr): ptr(obptr){}

   void setNull()
   {
      if(ptr)
         delete ptr;
      ptr=0;
   }

   void changeRsrc(someClass* obptr)
   {
      if(ptr)
         delete ptr;
      ptr=obptr;
   }

 someClass&amp; operator*()   { return *ptr;}
 someClass* operator-&gt;()  { return ptr;}
 ~Wrap(){ std::cout&lt;&lt;&quot;Destructor\n&quot;;delete ptr; ptr=0;}
};

void  Foo()
{
 /* someClass *somePtr = new someClass; */

 Wrap wObj(new someClass);
 /* Some Operations on someClass object using wObj */

 throw std::exception();
}

int main()
{
 try
 {
    Foo();
 }catch(std::exception&amp;){std::cout&lt;&lt;&quot;Exception caught\n&quot;;}
}</pre>
<p>Here, the class Wrap implements the RAII. When Foo() throws an exception, the wObj, being on the stack, invokes its destructor which frees the memory space taken up by the object of someClass. If the somePtr would have been used, then the space allocated by it would not have been freed.<br />
The <strong>auto_ptr</strong> is a class template, available in C++, that implements the RAII.</p>
<h3>10. What is RTTI? What are its uses?</h3>
<p>The RTTI or Run-Time Type Identification is a feature of C++ that helps in storing and retrieving type information of the objects at runtime. This information can be used for safely typecasting objects, and to fetch and utilize the type information to set the flow of the program at runtime.</p>
<p>The RTTI requires the classes in use to be <strong>&#8220;polymorphic&#8221;</strong> in nature, which means that there should be at least one virtual function defined in it. The system is used with the help of <strong>dynamic_cast&lt;&gt;</strong> and the <strong>typeid</strong> operator.</p>
<p>The typeid operator is available under the &#8220;typeinfo&#8221; header and can be used to find out the class to which a particular object belongs to, at runtime. The value returned by the operator is implementation-defined and hence, can be different across compilers. Thus, for portability sake, the operator can be used in the following manner:</p>
<pre class="brush: cpp;">#include&lt;iostream&gt;
#include&lt;typeinfo&gt;

struct dummyBase
{virtual ~dummyBase(){}};

struct dummyDer: dummyBase{};

void check(dummyBase* a)
{
   if(typeid(*a)==typeid(dummyBase))
      std::cout&lt;&lt;&quot;It is a dummyBase object\n&quot;;

   else if(typeid(*a)==typeid(dummyDer))
      std::cout&lt;&lt;&quot;It is a dummyDer object\n&quot;;
}

int main()
{
   dummyDer d;
   dummyBase b;
   dummyBase*ptr;

   ptr=&amp;d;
   check(ptr);

   ptr=&amp;b;
   check(ptr);
}</pre>
<p>If only the object information is required and no cast is to be done, then one must use the typeid operator and not the dynamic_cast because the former takes constant-time to return the value.</p>
<p>The dynamic_cast&lt;&gt; operator is what actually utilizes the RTTI system. The dynamic_cast&lt;&gt; is safe because if the cast is not possible, it sets the pointer to NULL instead of returning a bad pointer and in case of a reference, it throws the std::bad_cast exception. The cast knows about the hierarchy of the particular object that helps it do its work correctly and can be used to cast up, down or laterally.</p>
<p><strong>For Example:</strong></p>
<pre class="brush: cpp;">#include&lt;iostream&gt;

struct ITop
{
   virtual void funcTop()=0;
   virtual ~ITop(){}
};

struct ILeft: ITop
{
   void funcTop(){ std::cout&lt;&lt;&quot;ILeft funcTop\n&quot;;}
   virtual void funcLeft()=0;
};

struct IRight: ITop
{
   void funcTop(){ std::cout&lt;&lt;&quot;IRight funcTop\n&quot;;}
   virtual void funcRight()=0;
};

struct Left: ILeft
{
   void funcLeft(){ std::cout&lt;&lt;&quot;Left heir\n&quot;;}
};

struct Right: IRight
{
   void funcRight(){ std::cout&lt;&lt;&quot;Right heir\n&quot;;}
};

void Foo(ITop* elem)
{
   elem-&gt;funcTop();

   if(ILeft* ptrL = dynamic_cast&lt;ILeft*&gt;(elem))
      ptrL-&gt;funcLeft();
   else if(IRight* ptrR = dynamic_cast&lt;IRight*&gt;(elem))
      ptrR-&gt;funcRight();
}

int main()
{
   ITop* ptr[]={new Left, new Right};

   Foo(ptr[0]);
   Foo(ptr[1]);

   delete ptr[0];
   delete ptr[1];
}</pre>
<p>In the above code, the function Foo() checks the type of &#8216;elem&#8217; and finds out where does the object lie in the hierarchy and accordingly, invokes either the funcLeft() or the funcRight().</p>
<p><a href="http://www.objectmentor.com/resources/articles/acv.pdf">Here</a> is one good use of RTTI.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.interviewmantra.net/2010/04/cpp-hard-interview-questions-part2.html/feed</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>C++ Hard Interview Questions – part1</title>
		<link>http://www.interviewmantra.net/2010/02/cpp-hard-interview-questions-part1.html</link>
		<comments>http://www.interviewmantra.net/2010/02/cpp-hard-interview-questions-part1.html#comments</comments>
		<pubDate>Sat, 27 Feb 2010 12:00:00 +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[classes]]></category>
		<category><![CDATA[cpp interview questions]]></category>
		<category><![CDATA[destructor]]></category>
		<category><![CDATA[pointers]]></category>

		<guid isPermaLink="false">http://www.interviewmantra.net/?p=758</guid>
		<description><![CDATA[1. Why don&#8217;t we have virtual constructors? The virtual mechanism, though used without the knowledge of the complete type of the object, works only on fully-constructed objects. But, in order to create an object, the user is required to provide the complete information about the object. Thus, it is not possible for a constructor to [...]]]></description>
			<content:encoded><![CDATA[<h3>1. Why don&#8217;t we have virtual constructors?</h3>
<p>The virtual mechanism, though used without the knowledge of the complete type of the object, works only on fully-constructed objects. But, in order to create an object, the user is required to provide the complete information about the object. Thus, it is not possible for a constructor to be virtual.</p>
<h3>2. What is virtual destructor?</h3>
<p>Consider a class &#8220;Base&#8221; that is inherited by another class &#8220;Derived&#8221; and there exists a pointer-to-base referring to a heap-allocated derived object, then a virtual destructor would be required in the base class for the proper clean-up of the object. If the destructor is not virtual, then the destructor for the derived sub-object won&#8217;t be called and hence, the resources will not be freed.<span id="more-758"></span></p>
<p><strong>For Example:</strong></p>
<pre class="brush: cpp;">
#include&lt;iostream&gt;

struct Base
{
      Base(){std::cout&lt;&lt;&quot;Base object constructed\n&quot;;}
      ~Base(){std::cout&lt;&lt;&quot;Base object destructed\n&quot;;}
};

struct Derived: Base
{
      Derived(){std::cout&lt;&lt;&quot;Derived object constructed\n&quot;;}
      ~Derived(){std::cout&lt;&lt;&quot;Derived object destructed\n&quot;;}
};

int main()
{
      {
            Base b_Obj;
            Derived d_obj;
      }
      {
            Base *p_b = new Derived();
            delete p_b;
      }
}
</pre>
<p>In the above code, the b_obj and d_obj would be destructed properly but the object referred-to by the pointer p_b won&#8217;t be destructed properly until the base class&#8217; destructor is made virtual.</p>
<p>This is because when p_b is delete-ed, it calls the destructor of the static type of the pointer, which is Base, instead of the Dynamic type.</p>
<p>Thus, whenever it is possible that your class might be inherited by another class, it is safe to make the destructor virtual.<br />
<A name="Self"></A><br />
<h3>3. What is Self-Assignment? Does it have any bugs/problems associated with it?</h3>
<p>Assignment of an object to itself is known as self-assignment.</p>
<p><strong>For example:</strong></p>
<pre class="brush: cpp;">int func(int &amp;x, int &amp;y)
{
      x=x;   /* Self Assignment */

      x=y;   /* Self-Assignment, because x and y both refer to &quot;data&quot; [defined in main() ] */
}

int main()
{
      int data=10;
      fun(data, data);
}
</pre>
<p>One potential problem associated with self-assignment arises in the following code:</p>
<pre class="brush: cpp;">
class dummy
{
      int n;
      int *ptr;

public:
      dummy() : ptr(new int){ *ptr = 0; }
      ~dummy() {delete ptr;}

      dummy&amp; operator= (const dummy&amp; D)
      {
            delete ptr; /* #1 */
            ptr= D.ptr; /* #2 */
      }

      int* operator*()
      {
            return ptr;
      }
};

int main()
{
      dummy mObj(10);
      mObj = mObj;
}
</pre>
<p>Here, Line #1, delete-s the pointer ptr, which is then invalidated. Line #2 assigns that freed memory back to ptr. If the pointer is now used, it will invoke Undefined Behavior.</p>
<p>To prevent this, the = operator should first check for self-assignment.</p>
<pre class="brush: cpp;">
dummy&amp; operator= (const dummy&amp; D)
{
      if(*this==D)
            return *this;
      else
      {
            delete ptr;
            ptr = D.ptr;
            return *this;
      }
}
</pre>
<p><A name="copy"></A><br />
<h3>4. What do you mean by Shallow copy and Deep copy?</h3>
<p>Shallow copy and Deep copy are two ways of copying an object.<br />
Consider the following code</p>
<pre class="brush: cpp;">
class Dummy
{
      string d_str;
      int* d_ptr;
public:
      Dummy(string xstr, int* dptr) : d_str(xstr), d_ptr(pstr) {}
      ~Dummy() { delete d_ptr;}
};

int main()
{
      Dummy Xobj(&quot;Test_Object&quot;, new int);
      {
            Dummy Yobj = Xobj;
      }
}
</pre>
<p>A <strong>shallow copy</strong> of an object copies it bit-by-bit. This is what happens in the implicitly-defined assignment operator and copy constructor.</p>
<p>In the above example, the Xobj will be copied bit-by-bit into Yobj. Here, the copy constructor of Xobj.d_str will be first invoked to copy its contents into Yobj.d_str and then the Xobj.d_ptr would be copied  into Yobj.d_str and Yobj.d_ptr. The copy constructor of std::string has been defined to perform a Deep copy but the Xobj.d_ptr would be shallow-copied which means that Xobj.d_ptr and Yobj.d_ptr will both point to the same memory location and any change to one pointer will cause a change to the other.</p>
<p>The main problem occurs when an object goes out of scope or a pointer element is freed/invalidated. In the above example, Yobj will go out of scope and the memory pointed would be freed, causing both Xobj.d_ptr and Yobj.d_ptr to be invalidated and, thus, the user is not allowed to use Xobj.d_ptr any further.</p>
<p>A <strong>deep copy</strong> of Xobj into Yobj would cause the member Yobj.d_ptr to get hold of a new memory location and the contents of the memory be same as of those referred by the member Xobj.d_ptr. Now, as the memory location referred by Xobj.d_ptr and that by Yobj.d_ptr are different, deletion/invalidation of the memory causes no trouble to Xobj.</p>
<h3>5. What is the Placement new? Where would you use it? What are your responsibilities?</h3>
<p>The Placement new operator is used in case you want the object to be placed at a particular pre-allocated memory.</p>
<p><strong>For Example:</strong></p>
<pre class="brush: cpp;">
class test
{
      /* members and methods */
};

int main()
{
      char memory[sizeof(test)];
      char* position = memory;
      test* object = new(position) test;
}
</pre>
<p>Some situations where placement new can be used are :</p>
<ol>
<li>When writing your memory allocation unit and you want memory to be allocated from only a pre-allocated section of memory.</li>
<li>Used when it is required that I/O devices be mapped to specific memory addresses.</li>
<li>To create a shared memory region (for Inter-process Communication)</li>
</ol>
<p>There are a lot of other uses of placement new. Check <a href="http://stackoverflow.com/questions/362953/what-are-uses-of-the-c-construct-placement-new" target="_blank">here</a></p>
<p>When using placement new, the following points need to be kept in mind:</p>
<ol>
<li>Don&#8217;t use placement new unless you really need it and it is important that the object be places at some particular location in memory</li>
<li>It is the programmer&#8217;s job to check that the memory being used has enough space for the object and the memory is aligned properly.</li>
<li>The programmer is responsible for destruction the placed object, i.e., the programmer needs to call the destructor explicitly.</li>
</ol>
]]></content:encoded>
			<wfw:commentRss>http://www.interviewmantra.net/2010/02/cpp-hard-interview-questions-part1.html/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<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>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;">
#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;">
#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;">
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;">
#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;">
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;">
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;">
#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>0</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>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;">
#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;">
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;">
#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;">
#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>
		<item>
		<title>C++ Easy Interview Questions – part2</title>
		<link>http://www.interviewmantra.net/2009/12/cpp-easy-interview-questions-part2.html</link>
		<comments>http://www.interviewmantra.net/2009/12/cpp-easy-interview-questions-part2.html#comments</comments>
		<pubDate>Fri, 18 Dec 2009 12:00:34 +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++ pointers]]></category>
		<category><![CDATA[constructor]]></category>
		<category><![CDATA[cpp interview questions]]></category>
		<category><![CDATA[encapsulation]]></category>
		<category><![CDATA[object oriented concepts]]></category>
		<category><![CDATA[pointers]]></category>
		<category><![CDATA[polymorphism]]></category>

		<guid isPermaLink="false">http://www.interviewmantra.net/?p=448</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(First part here). 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 Easy. These [...]]]></description>
			<content:encoded><![CDATA[<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 <strong>Second part</strong> of the two parts of C++ interview questions(<a href="http://www.interviewmantra.net/2009/12/cpp-easy-interview-questions-part1.html">First part here</a>). 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>Easy</strong>.</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 is polymorphism? Explain with an example?</h3>
<p>Polymorphism is a way of providing a uniform interface with which different types of objects can interact and receive response based on the type itself. It can be said as &#8220;Same Work, Different Types&#8221;.<span id="more-448"></span></p>
<p>It is a common situation that objects of different types might have some common method, but depending on the type, the method needs to work differently.<br />
For ex: All shapes have area, but each shape has a different way of calculating it.</p>
<p>In C++, polymorphism is implemented using</p>
<ol>
<li>Function Overloading</li>
<li>Operator Overloading</li>
<li>Function Overriding (using virtual functions)</li>
</ol>
<p>In function overloading and operator overloading, the function to be used is decided at the compile-time itself.  But the binding of the call to the function in function overriding is done at the run-time.</p>
<p><strong>For Example:</strong></p>
<pre class="brush: cpp;">
#include&lt;iostream&gt;

float area(float a)
{
      std::cout&lt;&lt;&quot;(Circle)&quot;;
      return 3.14*a*a;
}

float area(float a, float b)
{
      std::cout&lt;&lt;&quot;(Rectangle)&quot;;
      return a*b;
}

int main()
{
      std::cout&lt;&lt;area(15)&lt;&lt;&quot;\n&quot;;
      std::cout&lt;&lt;area(10,12.50);
}
</pre>
<p>Decision regarding the function to be called is based upon the functions&#8217; signatures, which include the function name and the arguments(number and type).</p>
<h3>7. What is the use of the &#8216;volatile&#8217; keyword?</h3>
<p>The volatile keyword is a type-qualifier and is a signal to the compiler telling it</p>
<p>not to do any optimizations on the variable with this qualification.<br />
that the state of the variable can change anytime and the changes in the state could be due to some external control.</p>
<p>A variable should be declared volatile if its value can change unexpectedly.</p>
<p><strong>For Example:</strong></p>
<p>A variable shall be made volatile if</p>
<ol>
<li>It&#8217;s being shared between concurrent processes(threads).</li>
<li>Its value can be changed by some interrupt service routine.</li>
</ol>
<p>For further reading on volatile keyword, see <a href="http://www.netrino.com/Embedded-Systems/How-To/C-Volatile-Keyword" target="_blank">here</a>.</p>
<h3>8. What is Encapsulation?</h3>
<p>Encapsulation can be defined as a process of binding the attributes of an object with the associated methods, and way of implementing data hiding.</p>
<p>Using this feature of the object-oriented approach, one can implement a class such that its instances satisfy the definition of an object, i.e., each object has its attributes and properties, depending upon the type, and that no object, without specific permissions, can have access to the methods/attributes of a different type.</p>
<p><strong>For Example:</strong></p>
<p>In the following, an object of type Cat can&#8217;t bark. Similarly, a Dog can&#8217;t meow !!</p>
<pre class="brush: cpp;">
#include&lt;iostream&gt;
#include&lt;string&gt;

using std::string;

class Cat
{
      string Name;
      int Age;

public:
      Cat(string _name, int _age) : Name(_name), Age(_age){}
      void meow(){ std::cout&lt;&lt;&quot;Meow Meow!!&quot;;}
};

class Dog
{
      string Name;
      int Age;

public:
      Dog(string _name, int _age) : Name(_name), Age(_age){}
      void bark(){ std::cout&lt;&lt;&quot;Ruff Ruff!!&quot;;}
};
</pre>
<h3>9. What are dangling pointers?</h3>
<p>A pointer that doesn&#8217;t point to a valid memory location, i.e., it points to a storage that is no longer allocated is a dangling pointer.</p>
<p><strong>For Example:</strong></p>
<pre class="brush: cpp;">
int main()
{
      int *p = new int;
      /*Some Processing on p*/
      delete p;
      // Now p is a dangling pointer
}
</pre>
<p>It&#8217;s very useful to assign a deleted pointer to 0(zero) or NULL after delete-ing.</p>
<h3>10. What is the Constructor Initialization List?</h3>
<p>Whenever you create an object in C++, the constructor is invoked. It is responsible for the initialization of the data members of the class and for calling its parent class&#8217; constructor. The constructor initialization list is used for initializing the non-static data members of a class. The list follows the constructor signature after a single colon.</p>
<p><strong>For Example:</strong></p>
<pre class="brush: cpp;">
class myClass
{
      int x;
      string data;
public:
      myClass() : x(0), data() {}
      myClass( int a, string inp) : x(a), data(inp) {}
};
</pre>
<p>Here, the default constructor initializes x to 0 and makes data an empty string and the parametrised constructor initializes x to a and data to inp.</p>
<p>The order of members in the initialization list doesn&#8217;t matter because the initialization is always done in the order in which the data members are declared in the class. Similarly, the order of invocation of the parent class constructor depends upon the order in which parent classes are mentioned in the derivation list.</p>
<p><strong>For Example :</strong></p>
<pre class="brush: cpp;">
class base1
{
      int i;
public:
      base1() : i(0){}
      base1(int x) : i(x){}
};

class base2
{
      int j;
public:
      base2() : j(0){}
      base2(int x) : j(x){}
};

class der: public base1, public base2
{
      string data;
public:
      der(): data(), base1(), base2() {}
      der(int a, int b, string inp) : base2(b), data(inp), base1(a) {}
};
</pre>
<p>So, in the above initialization list for the class <strong>der</strong>, the order of initialization would be :<br />
Invoke base1&#8242;s constructor<br />
Invoke base2&#8242;s constructor<br />
Initialize &#8220;data</p>
]]></content:encoded>
			<wfw:commentRss>http://www.interviewmantra.net/2009/12/cpp-easy-interview-questions-part2.html/feed</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>C++ Easy Interview Questions &#8211; part1</title>
		<link>http://www.interviewmantra.net/2009/12/cpp-easy-interview-questions-part1.html</link>
		<comments>http://www.interviewmantra.net/2009/12/cpp-easy-interview-questions-part1.html#comments</comments>
		<pubDate>Fri, 18 Dec 2009 02:00:15 +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[classes]]></category>
		<category><![CDATA[coding practices]]></category>
		<category><![CDATA[cpp interview questions]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[main function]]></category>
		<category><![CDATA[namespace]]></category>
		<category><![CDATA[object oriented concepts]]></category>
		<category><![CDATA[structure]]></category>

		<guid isPermaLink="false">http://www.interviewmantra.net/?p=428</guid>
		<description><![CDATA[This post is a part of an ongoing series of C++ Interview Questions. This is first one of the two parts of C++ interview questions. Each part consists of 5 questions along with detailed answers. What&#8217;s common in all the questions in this set is that the level of difficulty is Easy. Read Part2 of [...]]]></description>
			<content:encoded><![CDATA[<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 one of the two parts of C++ interview questions. Each part consists of 5 questions along with detailed answers. What&#8217;s common in all the questions in this set is that the level of difficulty is <strong>Easy</strong>.</p>
<h3>Read <a href="http://www.interviewmantra.net/2009/12/cpp-easy-interview-questions-part2.html">Part2 of C++ Easy 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. We believe that you can&#8217;t get a better set of interview questions with the kind of quality of answers that you get here.</p>
<h3>1. Is the usage of void main() a good practice?</h3>
<p>No, the usage void main() is not a good coding practice.</p>
<p>The value returned from the main() is sent to the host environment or the parent process that calls your program. The parent might need to follow different paths depending on the success or failure of your program. Hence, one must always return a value from the program that returns its status back to the callee.</p>
<p>Moreover, the C++ standard specifies only two portable versions of the main() function &#8211; one that takes no parameters and the other that takes two parameters( an int and a array of pointer to char ), both of which return an int.</p>
<p>The versions are :</p>
<p>int main() {}</p>
<p>int main(int argc, char* argv[]){}</p>
<p>Any other signature of main() would be implementation dependent. Which means that the code that compiles on your compiler might not work on other compilers.</p>
<h3>2. What is an object?</h3>
<p>An Object, in the object-oriented terminology, is a real-world entity which has attributes and methods. An object is distinguished from another object by its identity. Every object has a type. Speaking in the language of C++, an object is an instance of a class.<span id="more-428"></span></p>
<p>In simple English, object is a concrete physical thing whose appearance and behavior can be described in words.</p>
<p>A simple example of an object would be my Dog, Lyca. In object oriented lingo, Dog is a Class and Lyca is an object of class Dog.</p>
<h3>3. Why is the size of an object of an empty class not zero?</h3>
<p>The size of an object of an empty class is not zero so that two objects of that class have different storage locations. If the size had been zero, then the new operator would have returned the pointer to the same location always.</p>
<p><strong>For Example:</strong></p>
<pre class="brush: cpp;">
#include&lt;iostream&gt;

class EmptyClass{};

int main()
{
      EmptyClass *object1 = new EmptyClass();
      EmptyClass *object2 = new EmptyClass();

     if(object1 == object2)
             std::cout&lt;&lt;&quot;Oops! This should not happen&quot;;
      else
            std::cout&lt;&lt;&quot;I love hamburgers!!&quot;;
}
</pre>
<p>If the size of the object of EmptyClass is zero, then object1 and object2 would have pointed to the same memory location.</p>
<p>Moreover, if the EmptyClass is used as a base class to some Derived class, then it is not necessary to provide a separate byte to the base sub-object of the Derived class&#8217; object. This means that the compiler can do some optimization so that the address of the derived class object is same as that of the first member of the derived sub-object.</p>
<p><strong>For Example:</strong></p>
<pre class="brush: cpp;">
#include&lt;iostream&gt;

class EmptyBase{};

class EmptyDerived: public EmptyBase
{
      public:
            int member;
};

int main()
{
      EmptyDerived der;

      int EmptyDerived::*member_ptr = &amp;EmptyDerived::member;

      void* ptr_der = static_cast&lt;void*&gt;(&amp;der);
      void* ptr_member= static_cast&lt;void*&gt;(&amp;(der.*member_ptr));

      if(ptr_der == ptr_member)
            std::cout&lt;&lt;&quot;Optimized compiler&quot;;
      else
            std::cout&lt;&lt;&quot;Still, no problem&quot;;
}
</pre>
<h3>4. What is the difference between a C++ class and a C++ structure?</h3>
<p>There is actually no difference between a class and structure in C++, except that the members of a struct are public by default and those of a class are private by default.</p>
<p><strong>For Example:</strong></p>
<pre class="brush: cpp;">
class UselessClass
{
      int x;
public:
      UselessClass(): x(0){}
      UselessClass(int a): x(a){}
};

struct UselessStruct
{
      UselessStruct(): x(0){}
      UselessStruct(int a): x(a){}
private:
      int x;
};
</pre>
<p>Both of these are functionally equivalent.</p>
<h3>5. What are namespaces?</h3>
<p>Namespaces are a way to group your classes, objects and functions under a single roof. It&#8217;s a way of defining a new scope.</p>
<p>Consider a situation when you are required to make use of a lot of external libraries in a C++ project. Also, assume that a lot of classes have been written by yourself. It may happen that the name of a class or a function you write clashes with that in an external library. This would lead to name collisions and ambivalence to the compiler.</p>
<p>A solution to this problem is to change the name of your class, which is a not a great option. How can external libraries steal your &#8216;right to name C++ codes&#8217;.</p>
<p>A cleaner way to solve this problem is to put your entities in a namespace.</p>
<p><strong>For Example:</strong></p>
<pre class="brush: cpp;">#include&lt;iostream&gt;
#include &quot;Glib.h&quot;

/* Glib is some Graphics Library with namespace Glib and class Circle. */

/* Your own Graphics namespace */
namespace stdShape
{
      class Circle
      {
            int centerX, centerY, Radius;
      public:
            Circle(int x, int y, int rad) : centerX(x), centerY(y), Radius(rad){}

            void draw();
            float area();
      };

      void Circle::draw()
      { /*Draw the shape on the screen*/
        std::cout&lt;&lt;&quot;Drawing stdShape Circle&quot;;
      }

      float Circle::area()
      { /*Return the area of given Shape*/
         return 3.141*Radius*Radius;
      }
}

int main()
{
/* Creating a Circle at (2,5) with radius 10 */
    stdShape::Circle myCircle(2,5,10);

    myCircle.draw();
    std::cout&lt;&lt;&quot;Area of myShape : &quot;&lt;&lt;myCircle.area();

/* Creating a Circle using GLib library */
    GLib::Circle GShape(10,12,6);
    GShape.draw();
}
</pre>
<p>Generally, the namespace and its inner declarations are written in a header file and the definitions for its elements are given in a separate cpp file. Then, the main C++ source file includes the header file.<br />
This means, we would have 3 files for this code:</p>
<p><strong>File1</strong> (stdShape.h)        that gives the declarations for the namespace and class<br />
<strong>File2</strong> (stdShape.cpp)     that includes stdShape.h and defines the class<br />
<strong>File3</strong> (main.cpp)           that incudes stdShape.h and Glib.h and defines the main() function</p>
<p><em>In near future, medium and hard level C++ questions would be added. <a href="http://subscribe.interviewmantra.net">Subscribe via Email</a> to be sure you don&#8217;t miss any updates.</em></p>
]]></content:encoded>
			<wfw:commentRss>http://www.interviewmantra.net/2009/12/cpp-easy-interview-questions-part1.html/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>
