Login | Register   
RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX

By submitting your information, you agree that devx.com may send you DevX offers via email, phone and text message, as well as email offers about other products and services that DevX believes may be of interest to you. DevX will process your information in accordance with the Quinstreet Privacy Policy.

Tip of the Day
Language: C++
Expertise: Intermediate
Sep 16, 1999



Building the Right Environment to Support AI, Machine Learning and Deep Learning

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.
Danny Kalev
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date