• Courses
  • Tutorials
  • Jobs
  • Practice
  • Contests

C++ Virtual Functions

Question 11

Can static functions be virtual? Will the following program compile? C
#include<iostream> 
using namespace std;    
 
class Test
{
   public:
      virtual static void fun()  { }
};
  • Yes
  • No

Question 12

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. C
#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 > b
  • a == b
  • a < b
  • Compiler Error

Question 13

C
#include <iostream>
using namespace std;
 
class A
{
public:
    virtual void fun() { cout << \"A::fun() \"; }
};
 
class B: public A
{
public:
   void fun() { cout << \"B::fun() \"; }
};
 
class C: public B
{
public:
   void fun() { cout << \"C::fun() \"; }
};
 
int main()
{
    B *bp = new C;
    bp->fun();
    return 0;
}
  • A::fun()
  • B::fun()
  • C::fun()

Question 14

Predict the output of following C++ program C
#include<iostream>
using namespace std;

class Base
{
public:
    virtual void show() { cout<<\" In Base \\n\"; }
};

class Derived: public Base
{
public:
    void show() { cout<<\"In Derived \\n\"; }
};

int main(void)
{
    Base *bp = new Derived;
    bp->Base::show();  // Note the use of scope resolution here
    return 0;
}
  • In Base
  • In Derived
  • Compiler Error
  • Runtime Error

There are 14 questions to complete.

Last Updated :
Take a part in the ongoing discussion