Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting from Derived* to Base*&

I was trying to answer the question mentioned here by passing the reference to the pointer instead of pointer to pointer like this:

class Parent 
{
};

class Child : public Parent 
{
};

void RemoveObj(Parent*& pObj)
{
    delete pObj;
    pObj = NULL;
}

int main()
{
    Parent* pPObj = new Parent;
    Child*  pCObj = new Child;
    pPObj = new Parent();
    pCObj = new Child();



    RemoveObj(pPObj);
    RemoveObj(pCObj); // This is line 32
    return 1;
}

But this produces the following compiler error at line 32:

error C2664: 'RemoveObj' : cannot convert parameter 1 from 'Child *' to 'Parent *&'

I agree that conversion from Child** to Parent** is not allowed. But why this conversion is also not allowed?

like image 808
Naveen Avatar asked Apr 10 '09 09:04

Naveen


People also ask

Can a derived pointer point to a base class?

Derived class pointer cannot point to base class.

Can a derived class become a base class?

A derived class can have only one direct base class. However, inheritance is transitive. If ClassC is derived from ClassB , and ClassB is derived from ClassA , ClassC inherits the members declared in ClassB and ClassA .

How do you call a derived class method in base?

A virtual function is a member function of a base class that is overridden by a derived class. When you use a pointer or a reference to the base class to refer to a derived class object, you can call a virtual function for that object and have it run the derived class's version of the function.

What is Upcasting and downcasting in C++?

Upcasting can cause object slicing when a derived class object is passed by value as a base class object, as in foo(Base derived_obj). Downcasting. The opposite process, converting a base-class pointer (reference) to a derived-class pointer (reference) is called downcasting.


3 Answers

An object of type Child* cannot be bound to a Parent*& for exactly the same reason that a Child** cannot be converted to a Parent**. Allowing it would allow the programmer (intentionally or not) to break type safety without a cast.

class Animal {};

class DangerousShark : public Animal {};

class CuteKitten : public Animal {};

void f(Animal*& animalPtrRef, Animal* anotherAnimalPtr)
{
    animalPtrRef = anotherAnimalPtr;
}

void g()
{
    DangerousShark myPet;
    CuteKitten* harmlessPetPtr;

    f(harmlessPetPtr, &myPet); // Fortunately, an illegal function call.
}

Edit

I think that some of the confusion arises because of the loose use of the words 'convert' and 'conversion'.

References can't be rebound, unlike objects which can be reassigned, so in the context of references when we speak of conversion we can only be concerned about initializing a new reference.

References are always bound to an object, and from the OP's question it was clear that he is aiming to get a reference that is a direct bind to an existing object. This is only allowed if the object used to initialize the reference is reference-compatible with the type of the reference. Essentially, this is only if the types are the same, or the type of the object is derived from the type of the reference and the reference type is at least as cv-qualified as the initializing object. In particular, pointers to different types are not reference-compatible, regardless of the relationship of the pointed-to types.

In other cases, a reference can be initialized with something that can be converted to the reference type. In these cases, though, the reference must be const and not volatile and the conversion will create a temporary and the reference will be bound to this temporary and not the original object. As pointed out, this is not suitable for the requirements of OP's motivating example.

In summary, a Child can be bound directly to a Parent& but a Child* cannot be directly bound to a Parent*&. A Parent* const& can be initialized with a Child*, but the reference will actually bind to a temporary Parent* object copy-initialized from the Child* object.

like image 113
CB Bailey Avatar answered Sep 18 '22 23:09

CB Bailey


  • Your classes don't have a virtual function. See FAQ 20.7

  • Beacuse Parent *& is a reference to a pointer to a Parent object. You are passing a pointer to a Child -- these are incompatible types. You can bind a temporary to a const-reference i.e. if you change your parameter to:

    void RemoveObj(Parent* const& foo);

But then you won't be able to do much with this.

It was just a test code so I didn't make any virtual destructors. If I understand correctly in the second call of RemoveObj(), I get a temporary Parent* object which can be passed as a const reference to the function. Is this correct?

I strongly suggest you run the following program in standard C++98 mode, once as in and then again after you have commented out foo(b) and uncommented delete b. Next, try putting in a virtual before ~s(). The differences should be self-explanatory!

#include <iostream>
using namespace std;
struct s { 
  s() {cout << __func__ << endl; }
  ~s() {cout << __func__ << endl; } 
};

struct t : s { 
   t() {cout << __func__ << endl; }
   ~t() {cout << __func__ << endl; } 
};

void foo(s* const& x) { delete x; }

int main() {
 t* b = new t;
 foo(b);
 //delete b;
}
like image 45
dirkgently Avatar answered Sep 19 '22 23:09

dirkgently


You can convert a Child* to a Parent*: this creates a temporary. But you cannot bind a non-const reference to that temporary.

That's not a problem of **/*&/etc. What you are trying to do is totally OK and makes sense. That Shark vs. Kitten has the same issue: not a matter of mixing kitten and sharks. You cannot bind a non-const reference to that unnamed pointer.

This is not the Parent** vs. Child** problem: there, if a Child** was a Parent**, then one could assign p[0] = new NotAChild;. A collection of objects which are all subtypes of A is not a collection of A.

like image 35
Benoît Avatar answered Sep 18 '22 23:09

Benoît