Why does the following code not break after delete bar? It seems like the object foo would have a reference to a deleted object and crash in printBar(). Is bar not really gone after the "delete bar" line?
I tried searching but all search results turn up more general information about references.Code:#include <cstdlib> #include <iostream> #include <string> using namespace std; class Bar { public: Bar() {} void print() { cerr << "Bar::print(), Hey there!!!!" << endl; } private: }; class Foo { public: Foo(Bar& b) : myBar(b) {} void printBar() { myBar.print(); } private: Bar& myBar; }; int main(int argc, char *argv[]) { Bar* bar = new Bar(); Foo* foo = new Foo(*bar); delete bar; bar->print(); for (int i = 0; i < 10; ++i) { foo->printBar(); } system("PAUSE"); return EXIT_SUCCESS; }
Thanks.




Reply With Quote