C++ Medium Interview Questions – part1


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 C++ Medium 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.

1. What are the POD types?

In C++, a POD or a Plain-Old Data type is either a scalar type or a POD class.

Scalar types are those that represent a single value. The int, float, bool, etc are scalar types.

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.

2. What are the container classes supported by C++ ?

C++ supports a number of container classes, divided into 3 categories:

  1. Sequence Containers:
    vector, deque and list.
  2. Associative Containers:
    map, multimap, set, multiset and bitset
  3. Adapters:
    stack, queue and priority_queue

3. What is the difference between delete and destructor in C++?

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.

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.

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 placement new. 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.

For Example:

#include<iostream>

class dummy
{
      int a;
public:
      dummy(): a(0)
      { std::cout<<"Default constructor\n"; }

      dummy(int x): a(x)
      { std::cout<<"Parametrized constructor\n";}

      ~dummy()
      { std::cout<<"Destructor\n";}
};

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

If the statement “delete ptr;” is removed, the destructor for the object won’t be called and the memory would not be freed.

4. What is function overloading and operator overloading?

Overloading is a method of implementing Polymorphism in C++.

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.

For Example:
One may want functions to add different types of data.

int add(int a, int b){return a+b;}

double  add(double a, double b){ return a+b;}

Now a call, say add(4, 5) would invoke the add function taking two int arguments.

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.

For Example:
A class Time can overload the + operator to add minutes and – operator to subtract minutes.

#include<iostream>

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& operator+(int minutes)
      {addMinutes(minutes); return *this;}

      Time& 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 */
}

5. What are virtual functions?

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.

It is used when the base class function can’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.

For example:
Consider a class ‘Shape’ 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().

The Shape class can’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.

#include <iostream>
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 << "Area : " << myShape->area();
      delete myShape;

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

      /* This will return Square's area */
      std::cout << "Area : " << myShape->area();
      delete myShape;
}

Note: It would be a good design practice to make the Shape class abstract because a Shape in itself doesn’t make sense.


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++ Medium Interview Questions – part1":

:Haha! I'am the first! Yeh~

Thank you!

Add a Comment / Trackback url

  1. #1  PrasoonNo Gravatar

    Very comprehensive and well written.

    09/12/20 08:38

Show all Show 5 so far Close all

Comment begin from here or jump up!