Skip to content
Related Articles

Related Articles

C++ | Virtual Functions | Question 12
  • Difficulty Level : Medium
  • Last Updated : 13 Oct, 2013

Predict the output of following C++ program. Assume that there is no alignment and a typical implementation of virtual functions is done by the compiler.




#include <iostream>
using namespace std;
  
class A
{
public:
    virtual void fun();
};
  
class B
{
public:
   void fun();
};
  
int main()
{
    int a = sizeof(A), b = sizeof(B);
    if (a == b) cout << "a == b";
    else if (a > b) cout << "a > b";
    else cout << "a < b";
    return 0;
}


(A) a > b
(B) a == b
(C) a < b
(D) Compiler Error


Answer: (A)

Explanation: Class A has a VPTR which is not there in class B.

In a typical implementation of virtual functions, compiler places a VPTR with every object. Compiler secretly adds some code in every constructor to this.


Quiz of this Question

Attention reader! Don’t stop learning now. Get hold of all the important C++ Foundation and STL concepts with the C++ Foundation and STL courses at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up
Recommended Articles
Page :