Note that there are some explanatory texts on larger screens.

plurals
  1. POC++ extern: pointer vs. reference
    text
    copied!<p>I have three classes: <code>ConsoleInputStream</code>, <code>ConsoleOutputStream</code>, <code>ConsoleErrorStream</code>. All of them are derived from <code>Stream</code>.</p> <p>Each stream has virtual functions <code>read</code> and <code>write</code>; as you guess, when user tries to use <code>ConsoleInputStream</code>'s <code>write</code> member function, it throws an error. Same happens when user tries to use <code>ConsoleOutputStream</code>'s <code>write</code> function.</p> <p>Now it's time to show the code.</p> <pre><code>// STREAM.HPP namespace streamlib { extern ConsoleInputStream stdin_default; extern ConsoleOutputStream stdout_default; extern ConsoleErrorStream stderr_default; extern Stream&amp; stdin; extern Stream&amp; stdout; extern Stream&amp; stderr; } // namespace streamlib // STREAM.CPP namespace streamlib { ConsoleInputStream stdin_default; ConsoleOutputStream stdout_default; ConsoleErrorStream stderr_default; Stream&amp; stdin = stdin_default; Stream&amp; stdout = stdout_default; Stream&amp; stderr = stderr_default; } // namespace streamlib // MAIN.CPP int main() { streamlib::stdout = streamlib::stdin; streamlib::stdout.write(); // Still working, but should have thrown error! } </code></pre> <p>However, everything works perfectly well when I define <code>stdin</code>, <code>stdout</code> and <code>stderr</code> as pointers instead of references, i.e. error is thrown as expected. But I don't want to allocate/free memory and use <code>-&gt;</code> operator where I could (could I?) use plain dot operator.</p> <p>The real situation is of course even more intricated: I also have some other types derived from <code>Stream</code> and just want to be able to quickly overload <code>stdin</code>, <code>stdout</code>, <code>stderr</code> streams with different kind of streams. Is it possible to do it with references?</p> <p>Thanks in advance!</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload