0

I created the following classes:

    class A
    {

    };
    class B :public A
    {
        public:
        void p()
        {
            cout<<"P";
        }
    };
    class C:public A
    {

    };

I tried to access the member function p() defined in class B using class C's dynamically created object.

    C* c = new C();
    ((B*)c)->p();

I was expecting that program will crash as there in no object of class B.But it worked and produced output p.How does it work?

  • *Undefined behavior* can sometime cause a crash. Or seemingly work. Or [summon nasal demons](http://catb.org/jargon/html/N/nasal-demons.html). Just don't do bad stuff. – Some programmer dude Mar 25 '20 at 08:10
  • And the big lesson here is to *never* use C-style casting, and instead see it as a sign that you're doing something wrong. – Some programmer dude Mar 25 '20 at 08:11
  • You need to get rid of the idea that bad C++ must cause a crash. It may cause a crash or it may not. Bad C++ code has *undefined behaviour*. – john Mar 25 '20 at 08:17
  • the method `P` is not using any members, hence it appears to work, doesn't mean that it does work in any meaningful sense – 463035818_is_not_an_ai Mar 25 '20 at 09:08

1 Answers1

1

It does not work. Your program has undefined behavior, which means that you have no guarantee on how the program will behave, as long as you don't have compiler-specific additional guarantees. It does not mean that you will get an error. It may seem to work, or it may not.

It is undefined behavior, because the explicit cast (B*)c will translate into

reinterpret_cast<B*>(c)

as static_cast<B*>(c) is invalid (because B is not derived from or base of C).

Because there is no B object at the address c, the resulting pointer will still point to the C object.

Calling the p() non-static member function through this pointer then has undefined behavior, because the pointer doesn't actually point to a B object.

walnut
  • 21,629
  • 4
  • 23
  • 59