Pages

Gin Rummy Indian Rummy Nine Men's Morris and more Air Attack

Tuesday, 14 April 2015

Advanced c++ interview questions and answers 2


1. What is the difference between calling just throw and throw with an object in a catch block?

SHOW/HIDE ANSWER
A copy of the object is created if we throw with an object. With just throw, no copy is created.

2. What is a possible replacement for c static function in c++?

SHOW/HIDE ANSWER
Unnamed namespaces.

3. What is the size of an empty class, or class with only normal functions?

SHOW/HIDE ANSWER
Not zero, 1 for most compilers. The reason for this is to have different address for different object.

4.  What is the size of class with only virtual functions?

SHOW/HIDE ANSWER
4 with most of the compilers for a 32bit binary.

5. Which class name the following program will print?

    1 #include <typeinfo>
    2 #include <iostream>
    3 
    4 class B
    5 {
    6 };
    7 
    8 class D: public B
    9 {
   10 };
   11 
   12 int main(int argc, char **argv)
   13 {
   14     B *t = new D();
   15     std::cout << typeid(*t).name() << std::endl;
   16 }
SHOW/HIDE ANSWER
B
For RTTI to work correctly we need atleast one virtual function in the base class.

6. What is the output of the following program?

    1 #include <iostream>
    2 
    3 void print(double v)
    4 {
    5     std::cout << v << std::endl;
    6 }
    7 
    8 void print(long v)
    9 {
   10     std::cout << v << std::endl;
   11 }
   12 
   13 int main(int argc, char **argv)
   14 {
   15     print(1);
   16 }
SHOW/HIDE ANSWER
Compilation error: ambiguous function call : print(long(1)) or print(double(1))?

7. What is the output of the following program?

    1 #include <iostream>
    2 
    3 void print(double v)
    4 {
    5     void print(long v);
    6     print(v);
    7 }
    8 
    9 void print(long v)
   10 {
   11     std::cout << v << std::endl;
   12 }
   13 
   14 int main(int argc, char **argv)
   15 {
   16     print(1.0);
   17 } 

8. What is the output of the following program?

    1 #include <iostream>
    2 
    3 class Base
    4 {
    5 public:
    6     void print(int v = 1)
    7     {
    8         std::cout << "Base : " << v << std::endl;
    9     }
   10 };
   11 
   12 class Derived: public Base
   13 {
   14 public:
   15     void print(int v = 10)
   16     {
   17         std::cout << "Derived : " << v << std::endl;
   18     }
   19 };
   20 
   21 
   22 int main(int argc, char **argv)
   23 {
   24     Derived o1;
   25     Base * o2 = &o1;
   26 
   27     o1.print();
   28     o2->print();
   29 
   30     return 0;
   31 }
SHOW/HIDE ANSWER

Derived : 10
Base : 1

9. How to declare a namespace alias?

SHOW/HIDE ANSWER
namespace MyLongNameSpaceName
{
...
}

namespace MLNSN = MyLongNameSpaceName;

10. Which is the macro that can be used to identify that we are using a c++ compiler?

SHOW/HIDE ANSWER
__cplusplus

11. How to declare c function in c++?

SHOW/HIDE ANSWER
By using extern "C".

extern "C" void print();

or

extern "C" {
    void print();
}

12. What is the difference between exit and abort?

SHOW/HIDE ANSWER
exit does a graceful process termination, it calls the destructors for all the constructed objects, with abort they are not called.
With exit the local With variables of the calling function and its callers will not have their destructors invoked.

13. Can I have static members in an union?

14. Which are the operators that cannot be overloaded?

15. Suppose we have an Integer class as shown below, how do I support 2+ obj?

    1 #include <iostream>
    2 
    3 class Integer
    4 {
    5     int mV;
    6 
    7 public:
    8     explicit Integer(int v)
    9      : mV(v)
   10     {}
   11 
   12     Integer operator+(int v) const
   13     {
   14         return Integer(mV+v);
   15     }
   16 
   17     int value() const
   18     {
   19         return mV;
   20     }
   21 };
   22 
   23 int main(int argc, char **argv)
   24 {
   25     Integer v1(2);
   26 
   27     std::cout << (v1+2).value() << std::endl;
   28     std::cout << (2+v1).value() << std::endl;
   29 }
SHOW/HIDE ANSWER
Add a global operator+ function which takes int as first argument and Integer as the second argument.

    1 Integer operator+(int v, Integer iv)
    2 {
    3     return iv+v;
    4 } 
 

16. Can I overload destructor?


17. Can I call destructor explicitly?

SHOW/HIDE ANSWER
Yes, but you only want to do that when you have used placement new. 

18. What is the output of the following program?


    1 #include <iostream>
    2 
    3 class Shape
    4 {
    5 public:
    6     virtual ~Shape()
    7     {};
    8     virtual void draw() = 0;
    9 };
   10 
   11 class Circle: public Shape
   12 {
   13 public:
   14     virtual void draw()
   15     {
   16         std::cout << "circle drawn" << std::endl;
   17     }
   18 };
   19 
   20 int main(int argc, char **argv)
   21 {
   22     Circle c;
   23     Shape *sp = &c;
   24 
   25     Circle *cp = &c;
   26     Shape **spp = &cp;
   27     
   28     (*spp)->draw();
   29 
   30     return 0;
   31 }
SHOW/HIDE ANSWER
Compilation error at 26; invalid conversion from ‘Circle**’ to ‘Shape**’

19. Where virtual inheritance should be used in a hierarchy?

SHOW/HIDE ANSWER
If we have a diamond class hierarchy we should use the virtual inheritance just below the top of the diamond

20. What is the output of the following program?

    1 
    2 #include <iostream>
    3 
    4 class Base
    5 {
    6 public:
    7     virtual ~Base()
    8     {}
    9 
   10     virtual void func1() = 0;
   11     virtual void func2() = 0;
   12 };
   13 
   14 class DerivedA: public virtual Base
   15 {
   16 public:
   17     void func1()
   18     {
   19         func2();
   20     }
   21 };
   22 
   23 class DerivedB: public virtual Base
   24 {
   25 public:
   26     void func2()
   27     {
   28         std::cout << "DerivedB::func2()" << std::endl;
   29     }
   30 };
   31 
   32 class Join: public DerivedA, public DerivedB
   33 {};
   34 
   35 int main(int argc, char **argv)
   36 {
   37     Join * j = new Join();
   38 
   39     DerivedA * da = j;
   40     DerivedB * db = j;
   41 
   42     da->func1();
   43     db->func1();
   44     
   45     delete j;
   46 
   47     return 0;
   48 }
SHOW/HIDE ANSWER
DerivedB::func2()
DerivedB::func2()

It is sometimes called "cross delegation". DerivedA ended up calling function of its sibling class DerivedB.


PREVIOUS HOME NEXT(Advanced c++ interview questions and answers 3)

Advanced c++ interview questions and answers 1


Let me assemble the c++ questions and answers so that I don't have to go elsewhere searching for questions for my next interview!

1. Can I call constructor from another constructor in the same class?

SHOW/HIDE ANSWER
No you can not do this. So the below given code snippet won't work.
    1 class Test
    2 {
    3 private:
    4     int mI;
    5 
    6 public:
    7     Test()
    8      : Test(0)
    9     {}
   10 
   11     Test(int i)
   12      : mI(i)
   13     {}
   14 };

However you can very much do this in c++11.

So is there a way to achieve it? Well yes. Its by using placement new, modified code is shown below.

    1 class Test
    2 {
    3 private:
    4     int mI;
    5 
    6 public:
    7     Test()
    8     {
    9         new (this) Test(100);
   10     }
   11     Test(int i)
   12      : mI(i)
   13     {}
   14 };
 

 

2. Do we need to call the base class operator= function from derived class, and how to do it?

SHOW/HIDE ANSWER
Yes you would need to call the base class assignment operator function, otherwise base class part of the variable won't set correctly. How to do it! see below,
    1 #include <iostream>
    2 
    3 class Base
    4 {
    5 private:
    6     int mBI;
    7 
    8 public:
    9     Base()
   10      : mBI(100)
   11     {}
   12 
   13     void setBValue(int i)
   14     {
   15         mBI = i;
   16     }
   17 
   18     void print() 
   19     {
   20         std::cout << "Base I " << mBI << std::endl;
   21     }
   22 };
   23 
   24 class Derived: public Base
   25 {
   26 private:
   27     int mDI;
   28 
   29 public:
   30     Derived()
   31      : mDI(1000)
   32     {}
   33 
   34     Derived & operator=(Derived const & o)
   35     {
   36         if (this != &o) {
   37             static_cast<Base &>(*this) = o;
   38             mDI = o.mDI;
   39         }
   40 
   41  return *this;
   42     }
   43 
   44     void setDValue(int i)
   45     {
   46         mDI = i;
   47     }
   48 
   49     void print() 
   50     {
   51         Base::print();
   52         std::cout << "Derived I " << mDI << std::endl;
   53     }
   54 };
   55 
   56 int main(int argc, char **argv)
   57 {
   58     Derived d1;
   59     Derived d2;
   60 
   61     d1.setBValue(1);
   62     d1.setDValue(1);
   63 
   64     d2 = d1;
   65 
   66     d1.print();
   67     d2.print();
   68 
   69     return 0;
   70 }

 

 3. Why do I need to return *this in an assignment operator function?

SHOW/HIDE ANSWER
To make assignment such as (obj3 = obj2) = obj1; to work.

 

4. How to declare and use pointer to member variable?

SHOW/HIDE ANSWER
    1 #include <iostream>
    2 
    3 class Test
    4 {
    5 public:
    6     int mI;
    7 };
    8 
    9 int main(int argc, char **argv)
   10 {
   11     Test d1;
   12     d1.mI = 100;
   13 
   14     int Test::*pmI = &Test::mI;
   15     d1.*pmI = 20;
   16 
   17     std::cout << "I " << d1.mI << std::endl;
   18 
   19     return 0;
   20 }

5. How to declare and use pointer to member function?

SHOW/HIDE ANSWER
    1 #include <iostream>
    2 
    3 class Test
    4 {
    5 public:
    6     int print() {
    7         std::cout << "Test::print" << std::endl;
    8     }
    9 };
   10 
   11 int main(int argc, char **argv)
   12 {
   13     Test d;
   14 
   15     int (Test::*pPrint)();
   16 
   17     pPrint = &Test::print;
   18     (d.*pPrint)();
   19 
   20     return 0;
   21 } 
 

6. What is the issue with the given program?

    1 #include <iostream>
    2 
    3 class Base
    4 {
    5 public:
    6     Base()
    7     {
    8         print();
    9     }
   10 
   11     virtual ~Base()
   12     {
   13         print();
   14     }
   15 
   16     virtual void print() = 0;
   17 };
   18 
   19 class Derived: public Base
   20 {
   21 public:
   22     Derived()
   23     {}
   24 
   25     void print()
   26     {
   27         std::cout << "Derived " << std::endl;
   28     }
   29 };
   30 
   31 int main(int argc, char **argv)
   32 {
   33     Derived d;
   34     return 0;
   35 } 
  
SHOW/HIDE ANSWER
Pure virtual function called from constructor and destructor!

7. What is the output of the following program?

    1 #include <iostream>
    2 
    3 class Test
    4 {
    5 private:
    6     int m1;
    7     int m2;
    8 
    9 public:
   10     Test()
   11      : m2(1),
   12        m1(m2)
   13     {}
   14 
   15     void print() const
   16     {
   17         std::cout << m1 << ", " << m2 << std::endl;
   18     }
   19 };
   20 
   21 
   22 int main(int argc, char **argv)
   23 {
   24     Test t;
   25     
   26     t.print();
   27 
   28     return 0;
   29 }
 
 
SHOW/HIDE ANSWER
Garbage value, 1
The problem is with the order of initialization list

8.How to initialize constant and reference member variable?

SHOW/HIDE ANSWER
Using initialization list.

9. What is constant in a const function?

SHOW/HIDE ANSWER
Variable 'this'.

10. How to modify member variable from a const funciton?

SHOW/HIDE ANSWER
Declare the member variables as mutable or use const_cast as shown below.
 
    1 #include <iostream>
    2 
    3 class Test
    4 {
    5 private:
    6     int m1;
    7     int m2; 
    8 
    9 public:
   10 
   11     void print() const
   12     {
   13         const_cast<Test *>(this)->m1 = 100;
   14         const_cast<Test *>(this)->m2 = 200;
   15         std::cout << m1 << ", " << m2 << std::endl;
   16     }
   17 };
   18 
   19 
   20 int main(int argc, char **argv)
   21 {
   22     Test t;
   23     t.print();
   24 
   25     return 0;
   26 }
 

11. What is the issue in the following program?

    1 #include <iostream>
    2 
    3 int main(int argc, char **argv)
    4 {
    5     const int & r1 = 100;
    6     int v = 200;
    7     int &r2 = v;
    8     int & r3 = 200;
    9     return 0;
   10 }
 
 
SHOW/HIDE ANSWER
Issue is in the initialization of r3 at line 8, rvalue should be a variable.

12. Can the destructor be pure virtual function?

SHOW/HIDE ANSWER
Yes, but you still have to define it!

 

13. What is the output of the following program?

    1 #include <iostream>
    2 
    3 class Base
    4 {
    5 public:
    6     Base()
    7     {
    8         print();
    9     }
   10 
   11     virtual ~Base()
   12     {
   13         print();
   14     }
   15 
   16     virtual void print() = 0;
   17 };
   18 
   19 class Derived: public Base
   20 {
   21 public:
   22     Derived()
   23     {}
   24 
   25     void print()
   26     {
   27         std::cout << "Derived" << std::endl;
   28     }
   29 };
   30 
   31 void Base::print()
   32 {
   33     std::cout << "Base" << std::endl;
   34 }
   35 
   36 int main(int argc, char **argv)
   37 {
   38     Derived *d = new Derived();
   39     d->print();
   40     delete d;
   41 
   42     return 0;
   43 }
SHOW/HIDE ANSWER
Base
Derived
Base

Some compiler will throw some warning on calling pure virtual function from constructor and destructor.

14. What is the output of the following program?

    1 #include <iostream>
    2 
    3 class Base
    4 {
    5 };
    6 
    7 class Derived: public Base
    8 {
    9 };
   10 
   11 int main(int argc, char **argv)
   12 {
   13     try {
   14         throw Derived();
   15     } catch (Base const & d) {
   16         std::cout << "Base" << std::endl;
   17     } catch (Derived const & d) {
   18         std::cout << "Derived" << std::endl;
   19     }
   20 
   21     return 0;
   22 } 
 
SHOW/HIDE ANSWER
Base

Exception will be handled by the first possible catch caluse.

15. What is the output of the following program?

    1 #include <iostream>
    2 
    3 class Exception
    4 {
    5 public:
    6     Exception()
    7     {
    8         std::cout << "Exception" << std::endl;
    9     }
   10     Exception(const Exception & o)
   11     {
   12         std::cout << "Exception Copy " << std::endl;
   13     }
   14 
   15     Exception & operator=(Exception const & o)
   16     {
   17         std::cout << "Exception Assign" << std::endl;
   18     }
   19 };
   20 
   21 void func(int i) {
   22     try
   23     {
   24         throw Exception();
   25     } catch (Exception const & e) {
   26         if (i) 
   27             throw e;
   28         else
   29             throw;
   30     }
   31 }
   32 
   33 int main(int argc, char **argv)
   34 {
   35     for (int i=0; i<2; ++i) {
   36         try {
   37             func(i);
   38         } catch (Exception const & d) {
   39             std::cout << "Caught Exception" << std::endl;
   40         }
   41     }
   42     return 0;
   43 }
 
SHOW/HIDE ANSWER
Exception
Caught Exception
Exception
Exception Copy
Caught Exception

16. What is the memory structure of an object?

SHOW/HIDE ANSWER
Usually C++ objects are made by concatenating member variables.
For example;


    1 class Test
    2 {
    3  int i;
    4  float j;
    5 };


is represented by an int  followed by a float.

    1 class TestSub: public Test
    2 {
    3  int k;
    4 };

The above class is represented by Test and then an int(for int k). So finally it will be int,  float and int.

In addition to this each object will have the vptr(virtual pointer) if the class has virtual function, usually as the first element in a class.


17. What is the difference between std::vector<int> x; and std::vector<int> x();?

SHOW/HIDE ANSWER
 First one declares a variable x of type std::vector<int>. Second one declares a function x which returns std::vector<int>.

18. What is a default constructor?

SHOW/HIDE ANSWER
1) A constructor which takes no argument
2) A constructor which has argument(s) but is(are) with default value

19. Can I use this pointer in the constructor?

SHOW/HIDE ANSWER
Yes, but try to avoid calling virtual function from the constructor and passing this pointer from the initialization list to other classes.
 

20. Does friends are inherited?

Friday, 27 March 2015

OpenGL ES 3.0 Programming in Android


Android introduced OpenGL ES 3.0 support from API level 18, Android 4.3 (JELLY_BEAN_MR2).

OpenGL ES 3.0 is a super set of OpenGL ES 2.0.

We will be creating an Android application which draw a simple rectangle using OpenGL ES 3.0.


Updating AndroidManifest.xml file

We will make sure that the application is installed on device which supports OpenGL ES 3.0 using uses-feature tag.

<uses-feature android:glEsVersion="0x00030000" android:required="true" />

And also the minimum SDK and target SDK will set to 18.

<uses-sdk android:minSdkVersion="18" android:targetSdkVersion="18" />

Main Activity implementation


Now lets create the Activity implementation. We will create a GLSurfaceView implementation and set it 
as the content view.

Our Activity class implementation is shown below,

    1 import android.app.Activity;
    2 import android.os.Bundle;
    3 
    4 public class MainActivity extends Activity {
    5     private GLES3View mView;
    6 
    7     @Override
    8     protected void onCreate(Bundle savedInstanceState) {
    9         super.onCreate(savedInstanceState);
   10         mView = new GLES3View(getApplication());
   11         setContentView(mView);
   12     }
   13 
   14     @Override
   15     protected void onPause() {
   16         super.onPause();
   17         mView.onPause();
   18     }
   19 
   20     @Override
   21     protected void onResume() {
   22         super.onResume();
   23         mView.onResume();
   24     }   
   25 }

View implementation

So far so good. Now lets go to the actual OpenGL ES 3.0 rendering.

What we will be doing is drawing a simple rectangle. Lets look at the vertex shader,
    1 #version 300 es
    2 layout(location = 0) in vec4 aPosition;
    3 void main()
    4 {
    5     gl_Position = aPosition;
    6 }

First line tells that we are going to use GLSL version 3.0. Next we declare our attribute variable. layout(location = 0) specifies the attribute index. See that we are not required to have glBindAttribLocation​ any more.
Rest of the statement is same as OpenGL ES 2.0 shader.

Now lets look at the fragment shader,

    1 #version 300 es
    2 precision mediump float;
    3 out vec4 fragColor;
    4 void main()
    5 {
    6     fragColor = vec4(1.0f, 1.0f, 0.0f, 1.0f);
    7 }

fragColor is out put variable. The value written to this variable is what will be written out into the color buffer. Here we will have an yellow rectangle.

Rest of the source code is almost similar to that of OpenGL ES 2.0 rendering, please note that we will be using android.opengl.GLES30 instead of android.opengl.GLES20.

Complete source code is given below,

    1 import java.nio.ByteBuffer;
    2 import java.nio.ByteOrder;
    3 import java.nio.FloatBuffer;
    4 
    5 import javax.microedition.khronos.egl.EGLConfig;
    6 import javax.microedition.khronos.opengles.GL10;
    7 
    8 import android.content.Context;
    9 import android.opengl.GLES30;
   10 import android.opengl.GLSurfaceView;
   11 import android.util.Log;
   12 
   13 public class GLES3View extends GLSurfaceView implements GLSurfaceView.Renderer {
   14 
   15     private static final String TAG = "GLES_3_HELLOWORLD";
   16     
   17     private static final String VertexShader = 
   18             "#version 300 es                               \n" +
   19             "layout(location = 0) in vec4 aPosition;       \n" +
   20             "void main()                                   \n" +
   21             "{                                             \n" +
   22             "    gl_Position = aPosition;                  \n" +
   23             "}                                             \n" +
   24             "                                              \n";
   25 
   26     private static final String FragmentShader = 
   27             "#version 300 es                               \n" +
   28             "precision mediump float;                      \n" +
   29             "out vec4 fragColor;                           \n" +
   30             "void main()                                   \n" +
   31             "{                                             \n" +
   32             "    fragColor = vec4(1.0f, 1.0f, 0.0f, 1.0f); \n" +
   33             "}                                             \n" +
   34             "";
   35 
   36     final int mPosLoc = 0;
   37 
   38     int mProgram;
   39 
   40     FloatBuffer mVerticesBuffer;
   41 
   42     public GLES3View(Context context) {
   43         super(context);
   44         
   45         // setup EGL configurations
   46         setEGLConfigChooser(8, 8, 8, 8, 16, 0);
   47         setEGLContextClientVersion(2);
   48         
   49         setRenderer(this);
   50     }
   51 
   52     private void init() {
   53         GLES30.glClearColor(0.5f, 0.5f, 0.5f, 1f);
   54         
   55         mProgram = createProgram(VertexShader, FragmentShader);
   56         
   57         // vertices
   58         float vertices[] = {
   59                 -0.75f, -0.75f,
   60                 0.75f, -0.75f,
   61                 0.75f, 0.75f,
   62                 -0.75f, 0.75f                
   63         };
   64         
   65         // create the float buffer
   66         ByteBuffer vbb = ByteBuffer.allocateDirect(vertices.length * 4);
   67         vbb.order(ByteOrder.nativeOrder()); 
   68         mVerticesBuffer = vbb.asFloatBuffer();
   69         mVerticesBuffer.put(vertices);
   70         mVerticesBuffer.position(0);
   71     }
   72 
   73     private void draw() {
   74         GLES30.glClear(GLES30.GL_COLOR_BUFFER_BIT);
   75         
   76         GLES30.glUseProgram(mProgram);
   77         
   78         GLES30.glVertexAttribPointer(mPosLoc, 2, GLES30.GL_FLOAT,
   79                                              false, 0, mVerticesBuffer);
   80         GLES30.glEnableVertexAttribArray(mPosLoc);
   81         
   82         GLES30.glDrawArrays(GLES30.GL_TRIANGLE_FAN, 0, 4);
   83     }
   84 
   85     private int loadShader(int shaderType, String source) {
   86         Log.d(TAG, source);
   87         
   88         int shader = GLES30.glCreateShader(shaderType);
   89         if (shader != 0) {
   90             // compile the shader
   91             GLES30.glShaderSource(shader, source);
   92             GLES30.glCompileShader(shader);
   93             
   94             int[] compiled = new int[1];
   95             GLES30.glGetShaderiv(shader, GLES30.GL_COMPILE_STATUS, compiled, 0);
   96             if (compiled[0] == 0) {
   97                 Log.e(TAG, GLES30.glGetShaderInfoLog(shader));
   98                 GLES30.glDeleteShader(shader);
   99                 shader = 0;
  100             }
  101         }
  102         
  103         return shader;
  104     }
  105 
  106     private int createProgram(String vertexSource, String fragmentSource) {
  107         int vertexShader = loadShader(GLES30.GL_VERTEX_SHADER, vertexSource);
  108         if (vertexShader == 0) {
  109             return 0;
  110         }
  111 
  112         int pixelShader = loadShader(GLES30.GL_FRAGMENT_SHADER, fragmentSource);
  113         if (pixelShader == 0) {
  114             return 0;
  115         }
  116 
  117         int program = GLES30.glCreateProgram();
  118         if (program != 0) {
  119             GLES30.glAttachShader(program, vertexShader);
  120             GLES30.glAttachShader(program, pixelShader);
  121             GLES30.glLinkProgram(program);
  122             int []linkStatus = {0};
  123             GLES30.glGetProgramiv(program, GLES30.GL_LINK_STATUS, linkStatus, 0);
  124             if (linkStatus[0] != 1) {
  125                 Log.e(TAG, GLES30.glGetProgramInfoLog(program));
  126                 GLES30.glDeleteProgram(program);
  127                 program = 0;
  128             }
  129         }
  130         return program;
  131     }
  132     
  133     public void onDrawFrame(GL10 gl) {
  134         draw();
  135     }
  136 
  137     public void onSurfaceChanged(GL10 gl, int width, int height) {
  138         GLES30.glViewport(0, 0, width, height);
  139     }
  140 
  141     public void onSurfaceCreated(GL10 gl, EGLConfig config) {
  142         init();
  143     }
  144 }

Complete source code can be found at https://github.com/trsquarelab/glexamples/tree/master/android/gles_3_helloworld