Thursday, July 30, 2009

Can a C++ reference hold a reference to a child of it's class?

For C++ gurus.





Consider the following code snippets:





ostream %26amp; outfile=cout; // assign stdout to a reference of ostream





Then I may want to do something like this:


ofstream* alternate_op=new ofstream("my_output.txt");


outfile=(ostream %26amp;) *alternate_op;





Now outfile points to my alternate output file instead of stdout. Fine. In MS Visual C++ 6.0 this works out just the way I want it. But other compilers (such as MingW for Windows) complain with messages like:





741 C:\Dev-Cpp\include\c++\3.4.2\bits\ios_ba... `std::ios_base%26amp; std::ios_base::operator=(const std::ios_base%26amp;)' is private





So, is my solution the best one? Or is there a better way? I want to be able to dynamically use either stdout (cout) or my own o/p file stream along with operator%26lt;%26lt; to format output without a lot of fooling around about which one I'm really using. And I'd like my solution to be as portable between compilers as possible.

Can a C++ reference hold a reference to a child of it's class?
Biting my tongue and not taking an obligatory swipe at VC.





Assuming you can, just change the reference to a pointer and you are good to go.








int main ()


{


ostream* outfile = %26amp;cout; // assign stdout to a POINTER to ostream





*outfile %26lt;%26lt; "Hello\n";





ofstream* alternate_op=new ofstream("my_output.txt");





outfile = alternate_op;





*outfile %26lt;%26lt; "World" %26lt;%26lt; endl;





}
Reply:You could run into a dangling pointer problem.
Reply:In C++ you can't reassign a reference. I don't know why VC6 allows you to do it, but it shouldn't. When you assign to a reference, you actually assign to the value being referenced. In this case your code is trying to change the value of cout.

sympathy flowers

No comments:

Post a Comment