-4

I am new in C++. I don't know why we cant able to create Derived Class Reference.In derived class all the features of base will get in this case, then also why..Please help me with exact reason.If this is a duplicate one please share me the exact link.

#include<iostream>  
using namespace std;  
struct A  
{  
  virtual void get()  
  {   
    cout<<"I am in Base"<<endl;  
  }  
};

struct B:A  
{
  virtual void get()
  {
    cout<<"I am in Derived"<<endl;
  }  
};

int main()  
{  
  B*ptr = new A();  // virtual.cpp:21: error: invalid conversion from A* to B*  
  ptr->get();
  return 0;
}  
Walter
  • 44,150
  • 20
  • 113
  • 196

1 Answers1

0
  1. What you want to assign to is not a reference but a pointer.
  2. B is derived from A, so B is an A. But A is not a B.
  3. Thus A*ptr=new B; is allowed, but not what you want.
  4. Suppose B*ptr=new A; was possible. If B contains data members which A doesn't have, interpreting A as B makes no sense and trying to access those members will at best cause a crash.

Btw, this is not a C++ tutorial site. I recommend to read a beginner's book.

Walter
  • 44,150
  • 20
  • 113
  • 196