Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Derived * to Base * but not Derived ** to Base ** - why ?

Status
Not open for further replies.

areza123

Programmer
Jul 4, 2002
60
IN
Consider the following block of code:

#include <iostream>
using namespace std;

class Base {
public:
Base();
virtual void show();
};

class Derived:public Base {
int d;
public:
Derived();
virtual void show();
private:
};

Base::Base() {}

void Base::show(){
cout << &quot;In show base&quot; << endl;
}

Derived::Derived() {}

void Derived::show() {
cout << &quot;In show derived&quot; << endl;
}

int main()
{
// Assign a Derived * object to a Base * pointer
// Note - u cannot assign a Base * object to a Derived * ptr
Derived *d = new Derived;
Base *b = d;
if (b) {
b->show();
}

Derived **dd = &d;
(*dd)->show();
Base **bb = dd; // compilation error - why ?
}


C++ lets me assign a Derived object pointed to by a Derived * to a Base *
But a Derived object pointed to by a Derived ** cannot be initialized to a Base ** - Why ?

Derived *d = new Derived;
Base *b = d;
IS OK !!
But,
Derived **dd = &d; // Ok again
Base **bb = dd; // compilation error - why ?

Cheers
 
try:
Base **bb = (Base **)dd;

Ion Filipski
1c.bmp

ICQ: 95034075
AIM: IonFilipski
filipski@excite.com
 
As a general rule I recommend you should avoid c-style casting. Use c++ castings instead, they are safer as they provide means of detecting if a casting fails.

dynamic_cast, reinterpret_cast etc



/Per

if (typos) cout << &quot;My fingers are faster than my brain. Sorry for the typos.&quot;;
 
>> Base **bb = dd; // compilation error - why ?

Because the standard says the compiler will generate ONE implicit type conversion. You would need more than one conversion in that statement due to the &quot;pointer-to-pointer&quot; de-referencing. Therefore you need to provide explicit casts either the old C style or as Perf says using C++ casting operators.


-pete
 
Thank you people. I tried using different C++ style casts and was surprised to know that both static and dynamic casts result in compilation errors, but reinterpret_cast is fine - does anybody have an explanation to this ?

Base **bb = static_cast <Base **>(dd)
// the static_cast does not work...
// comilation error: static_cast from `Derived **' to `Base **'
Base **bb = dynamic_cast<Base **>(dd);
// comilation error: cannot dynamic_cast `dd' (of type `class Derived **') to type `class Base **'

Base **bb = reinterpret_cast<Base **>(dd); // fine - why ?
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top