0

I'm passing references to pointers in order to use virtual functions.

Option 1 does what I intended and calls the appropriate derived class virtual function. Option 2 does not, suggesting no reference was passed. Since this does compile, then what does & mean in this context if not pass by reference?

1. Derived aDerived; Derived *pDerived = &aDerived; 2. Derived *pDerived = &Derived(); 
17
  • 3
    Option 2 shouldn't compile in standard C++. Also, nowhere are you passing references to pointers here. Commented Feb 9, 2017 at 23:06
  • 2
    Why do you need to "pass references to pointers in order to use virtual functions"? Commented Feb 9, 2017 at 23:07
  • 1
    In your first example, & is the address-of operator, it has nothing to do with references. Commented Feb 9, 2017 at 23:08
  • 1
    @cafekaze That compiler has some a non-standard "extension" that allows you to write this. I'm pretty sure it can be switched off with some flag. Commented Feb 9, 2017 at 23:16
  • 1
    @cafekaze There's nothing wrong with using references if you actually use references. C++ virtual functions work on pointers, there's no need to use references at all if you don't want to. In many cases references help with readability and encourage the compiler to make more optimizations, so they're a good idea, but there's no rule like you're describing. I think you're coming at this with a whole lot of mistaken assumptions that are a symptom of having insufficiently robust reference material. Get the Bjarne book as a start. Commented Feb 9, 2017 at 23:17

1 Answer 1

1

In option 2 you are attempting to take the address of an rvalue. This should fail to compile with:

error: lvalue required as unary ‘&’ operand

Check this live example.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks - revised VS warning level to 4 and it showed basically what you mentioned.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.