-1

Below is code snippet,

#include <iostream>

using namespace std;

class A
{
public:
    void print() const
    {
        cout << "In A::print()\n";
    }

    virtual void show()
    {
        cout << "In A::show()\n";
    }
};

class B : public A
{
public:
    void print() const
    {
        cout << "In B::print()\n";
    }

    void show()
    {
        cout << "In B::show()\n";
    }
};

int main() {
    A* a = new A;
    a->show();
    a->print();

    B* b = dynamic_cast<B*>(a);
    cout << b << endl;
    b->print();
    b->show();

    return 0;
}

Here is output when I run this (I am using Visual c++ compiler),

In A::show()
In A::print()
00000000
In B::print()

and then program stops working ....

There are two questions, 1. Why/How call to function B::print() is successful even after dynamic_cast is failed since value of b is 0 as seen in output?

  1. Why program stopped working when B::show() is called (given that call to B::print() was successful in line before it)?
Pravar Jawalekar
  • 605
  • 1
  • 6
  • 18
  • 2
    you should understand the difference btw it does not guarantee to work and it guarantees not to work. Nobody requires compiler to generate code to fail explicitly. – Slava Nov 17 '15 at 15:46
  • Not quite duplicate. Here, 'this' pointer is used implicitly, by VMT, in the second case – AndreyS Scherbakov Nov 17 '15 at 16:02

1 Answers1

1

No surprise.

  1. b is NULL as dynamic cast is failed
  2. b->print() is ok. Well, this is NULL but it never used in its body.
  3. b->show() fails. Despite it also doesn't use this explicitly, it still needs a Virtual Methods table lookup to determine the proper subclass method address. A pointer to the virtual table is a (hidden) field of B class; as b is NULL, program crashes.
AndreyS Scherbakov
  • 2,674
  • 2
  • 20
  • 27