-1
#include "stdafx.h"
#include <iostream>
using namespace std;
class myclass {
public:
    int a;
    myclass() : a(-1){};
 };
class derivedclass : public myclass {
     public: 
     int b;
    derivedclass() : b(-2) {};
  };

int main()
{
myclass* p= new myclass;
//  derivedclass* pd = dynamic_cast<derivedclass*>(p);
derivedclass* pd = static_cast<derivedclass*>(p);
cout << pd->b << endl;

return 0;
}

I have two questions.

  1. dynamic_cast is not working. So need to add a virtual function in myclass?
  2. why pd->b is not -2 as is initialized in the constructor?
Taitai
  • 584
  • 2
  • 7
  • 18
  • 2
    An instance of `myclass` never could become an instance of `derivedclass` magically. – πάντα ῥεῖ Oct 30 '18 at 23:27
  • 1
    @πάνταῥεῖ is right. dynamic_cast is for casting a base class pointer to a derived class pointer. But the pointed to object must be a derived class. Try `myclass* p= new derivedclass; derivedclass* pd = dynamic_cast(p);` – Jerry Jeremiah Oct 31 '18 at 00:04

2 Answers2

2

The dynamic_cast is not working for two reasons.

One is that, as you guessed, you need virtual functions for dynamic_cast to work, which is to say that the base type myclass must be polymorphic.

The other reason also addresses your second question. In your code, derivedclass inherits from myclass. This implies that any object of type derivedclass is also an object of type myclass. It does not imply that any object of type myclass is necessarily also of type derivedclass, which you seem to be assuming.

// creates a new instance of myclass, NOT an instance of derivedclass
myclass* p= new myclass;

// assuming myclass is polymorphic, returns a type-safe pointer to a derivedclass object
// if p is not such an object, returns nullptr, which is useful for error checking
derivedclass* pd1 = dynamic_cast<derivedclass*>(p);

// this is very unsafe! pd2 is now a 'wild' pointer to an object that doesn't exist
derivedclass* pd2 = static_cast<derivedclass*>(p);

// this is Undefined Behavior: there is no such `b` in memory at pd2, and that memory
// is not yours to read from
cout << pd2->b << endl;

The reason that pd->b is not -2 is because the constructor of derivedclass never ran. You never created an object of derivedclass.

alter_igel
  • 6,899
  • 3
  • 21
  • 40
1

dynamic_cast is not working. So need to add a virtual function in derivedclass?

Yes. You do need to have a virtual function in order to use dynamic cast.

Also, you must check whether dynamic cast results in a null pointer. In this case, it would result in null (if there was a virtual function), since p does not point to an instance of derivedclass.

why pd->b is not -2 as is initialized in the constructor?

The behaviour is undefined. No derivedclass or its members was ever constructed.

eerorika
  • 232,697
  • 12
  • 197
  • 326