Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


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

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.

 

 

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