© 2014 Firstsoft Technologies (P) Limited. login
Hi 'Guest'
Home SiteMap Contact Us Disclaimer
enggedu

C and C++ Interview Questions

11. Define namespace

Ans:

It is a feature in c++ to minimize name collisions in the global name space. This namespace keyword assigns a distinct name to a library that allows other libraries to use the same identifier names without creating any name collisions. Furthermore, the compiler uses the namespace signature for differentiating the definitions.

Ex 1: Find the output of the following program

class some{
public:
            ~some()
            {
                        cout<<"some's destructor"<<ENDL;
            }
};
 
void main()
{
            some s;
            s.~some();
}

Ans:
            some's destructor
            some's destructor

Explanation:

Destructors can be called explicitly. Here 's.~some()' explicitly calls the destructor of 's'. When main() returns, destructor of s is called again, hence the result.

Ex 2: Find the output of the following program
 
#include
 
class fig2d
{
            int dim1;
            int dim2;
 
public:
            fig2d() { dim1=5; dim2=6;}
 
            virtual void operator<<(ostream & rhs);
};
 
void fig2d::operator<<(ostream &rhs)
{
            rhs <dim1<<" "<dim2<<" ";
}
 
/*class fig3d : public fig2d
{
            int dim3;
public:
            fig3d() { dim3=7;}
            virtual void operator<<(ostream &rhs);
};
void fig3d::operator<<(ostream &rhs)
{
            fig2d::operator <<(rhs);
            rhs<dim3;
}
*/
 
void main()
{
            fig2d obj1;
//          fig3d obj2;
 
            obj1 << cout;
//          obj2 << cout;
}

Ans :
            5 6


Explanation:            

In this program, the << operator is overloaded with ostream as argument. This enables the 'cout' to be present at the right-hand-side. Normally, 'cout' is implemented as global function, but it doesn't mean that 'cout' is not possible to be overloaded as member function.    Overloading << as virtual member function becomes handy when the class in which it is overloaded is inherited, and this becomes available to be overrided. This is as opposed to global friend functions, where friend's are not inherited.

SLogix Student Projects
bottom