<?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; classes</title>
	<atom:link href="http://www.interviewmantra.net/tag/classes/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++ 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[<p></p><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; title: ; notranslate">
#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; title: ; notranslate">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; title: ; notranslate">
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; title: ; notranslate">
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; title: ; notranslate">
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; title: ; notranslate">
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>2</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></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++ 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></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 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; title: ; notranslate">
#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; title: ; notranslate">
#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; title: ; notranslate">
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; title: ; notranslate">#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>

<!-- 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:17:25 -->
