2

I have a question on assigning a derived class object with base class pointer...

class Base 
{ 
    void print() { cout<<"Class Base"; }

};

class Derived: public Base
{ 
    void print() {  cout<<"class Derived"; }

};

int main()
{
    Base b, *bp;
    Derived d, *dp;

    b.print();
    d.print();
    bp = d; // why is this a conversion error? getting an error "cannot convert ‘Derived’ to ‘Base*’ in assignment"

    bp = new B(); // this works fine...

}    

Does it mean that we can only assign a dynamically allocated derived class object to a base class pointer?? why is that so???

2 Answers2

7

bp is a pointer here, and you are trying to assign an object to it. Try assigning the address of that object instead: bp = &d;

jweyrich
  • 31,198
  • 5
  • 66
  • 97
Brett Hale
  • 21,653
  • 2
  • 61
  • 90
0

Derived isn't a pointer, its an object. You need to get the address of that object to assign it to a pointer (which holds an address!):

bp = &d;

Works fine.

John Humphreys
  • 37,047
  • 37
  • 155
  • 255