devxlogo

Inheritance and a Reference to a Base Pointer

Inheritance and a Reference to a Base Pointer

A reader posted this question on one of the C++ newsgroups. Assuming B is a base class for D, his program looks like this:

   void g (B* p) ;  void f (B*& p); // modifies p  int main ()  {    D* p = NULL ;    g (p) ;  // fine    f (p) ;  /* error: "cannot convert parameter 1 from 'class D *' to                    'class B *& ' a reference that is not to 'const' cannot                    be bound to a non-lvalue" */  }

Function f() works as expected, but g() causes a compilation error. The reader wondered what was wrong with the invocation of f() in main(). Can you see what is wrong with it? p is a D*, not a B*, and to convert it to a B*, the implementation creates a temporary pointer (recall that a reference must be bound to a valid object; in this case, a pointer). Now because temporaries are rvalues, and you can’t bind an rvalue to a non-const reference, the compiler complains. Declaring f() as follows:

   void f (D* & p) { /* modifies p */ }

solves this problem.

devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist