I was trying to understand how to apply polymorphism in C++ by creating a base class Document
from which the two classes Book
and Newspaper
are derived. Note how the virtual method get_content()
is overridden inside the derived classes.
class Document {
public:
virtual std::string get_content() const { return ""; }
};
class Book : public Document {
public:
std::string get_content() const override { return "Book"; }
};
class Newspaper: public Document {
public:
std::string get_content() const override { return "Newspaper"; }
};
The Document
class is aggregated with the Printer
class (by reference), and the get_content()
method of the appropriate derived class is called according to the type of document.
class Printer {
public:
const Document& m_doc;
Printer(const Document& doc): m_doc(doc) {
std::cout << "Printing... " << m_doc.get_content() << std::endl;
}
std::string get_content() const { return m_doc.get_content(); }
};
Until now everything works well, but once I aggregate the Printer
class with another class Binding
, the get_content()
doesn't seem to call the method of the right derived class anymore.
class Binding {
public:
Printer m_printer;
Binding(const Printer& printer): m_printer(printer) {
std::cout << "Binding... " << m_printer.get_content() << std::endl;
}
};
I don't understand why the following piece of code...:
int main() {
Printer p1(Book{});
Printer p2(Newspaper{});
Binding b1(p1);
Binding b2(p2);
}
...shows Binding... Newspaper
at the third line while the Printing
is clearly getting a Book
instance as an input:
Printing... Book
Printing... Newspaper
Binding... Newspaper
Binding... Newspaper
Having m_printer
declared as a reference inside Binding
class doesn't fix this problem either.
Printer p1(Book{});
Printer p2(Newspaper{});
Here, you are using temporary objects. These objects are destroyed at the end of the statement they are created in.
So, you have dangling references. Calling methods on a dangling reference is undefined behaviour.
In C++, you are in charge of object lifetime.
(Reference lifetime extension does not apply here)
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments