C++ Easy Interview Questions – part1


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’s common in all the questions in this set is that the level of difficulty is Easy.

Read Part2 of C++ Easy Interview Questions

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’t get a better set of interview questions with the kind of quality of answers that you get here.

1. Is the usage of void main() a good practice?

No, the usage void main() is not a good coding practice.

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.

Moreover, the C++ standard specifies only two portable versions of the main() function – 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.

The versions are :

int main() {}

int main(int argc, char* argv[]){}

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.

2. What is an object?

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.

In simple English, object is a concrete physical thing whose appearance and behavior can be described in words.

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.

3. Why is the size of an object of an empty class not zero?

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.

For Example:

#include<iostream>

class EmptyClass{};

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

     if(object1 == object2)
             std::cout<<"Oops! This should not happen";
      else
            std::cout<<"I love hamburgers!!";
}

If the size of the object of EmptyClass is zero, then object1 and object2 would have pointed to the same memory location.

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’ 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.

For Example:

#include<iostream>

class EmptyBase{};

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

int main()
{
      EmptyDerived der;

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

      void* ptr_der = static_cast<void*>(&der);
      void* ptr_member= static_cast<void*>(&(der.*member_ptr));

      if(ptr_der == ptr_member)
            std::cout<<"Optimized compiler";
      else
            std::cout<<"Still, no problem";
}

4. What is the difference between a C++ class and a C++ structure?

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.

For Example:

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;
};

Both of these are functionally equivalent.

5. What are namespaces?

Namespaces are a way to group your classes, objects and functions under a single roof. It’s a way of defining a new scope.

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.

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 ‘right to name C++ codes’.

A cleaner way to solve this problem is to put your entities in a namespace.

For Example:

#include<iostream>
#include "Glib.h"

/* 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<<"Drawing stdShape Circle";
      }

      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<<"Area of myShape : "<<myCircle.area();

/* Creating a Circle using GLib library */
    GLib::Circle GShape(10,12,6);
    GShape.draw();
}

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.
This means, we would have 3 files for this code:

File1 (stdShape.h) that gives the declarations for the namespace and class
File2 (stdShape.cpp) that includes stdShape.h and defines the class
File3 (main.cpp) that incudes stdShape.h and Glib.h and defines the main() function

In near future, medium and hard level C++ questions would be added. Subscribe via Email to be sure you don’t miss any updates.


About the Author:  Saurabh Manchanda is a whiz C/C++ programmer. He is currently pursuing his Bachelors of Technology degree in Computer Science. His passions are programming, studying algorithms and solving puzzles. He loves reading books, technical textbooks and fiction novels. When not programming, he could be seen playing pool or cricket or watching movies, listening to songs or staring at his pet fishes! You can connect him at Orkut, Facebook, follow him on Twitter or contact him at saurabh29789@gmail.com If you are thankful for his posts, you may want to gift an item from his Amazon Wish List.



All comments of post - "C++ Easy Interview Questions – part1":

:Haha! I'am the first! Yeh~

Thank you!

Add a Comment / Trackback url

Comment begin from here or jump up!


All trackbacks / pingbacks of the post "C++ Easy Interview Questions – part1":

http://www.interviewmantra.net/2009/12/cpp-easy-interview-questions-part1.html/trackback