Having the following class hierarchy with virtual method and virtual destructor, what will be printed as a result of the program execution?
#include <iostream>

class A
{
private:
    virtual void VirtualMethod()
    {
        std::cout << "A::VirtualMethod()";
    }

public:
    void TestMethod()
    {
        VirtualMethod();
    }

    virtual ~A() {}
};

class B : public A
{
private:
    void VirtualMethod()
    {
        std::cout << "B::VirtualMethod()";
    }

public:
    ~B() {}
};

int main()
{
    A* a = new B();
    a->TestMethod();
    delete a;

    return 0;
}
Explanation
Maybe the most obvious answer at first glance is compilation error cause we try to call private method of B class. But existence of virtual method cause dynamic binding for this method, hence compiler won't check at compilation stage whether method public or not

Follow CodeGalaxy

Mobile Beta

Get it on Google Play
Send Feedback
Cosmo
Sign Up Now
or Subscribe for future quizzes