A base interface should usually provide the operations its callers need. Occasionally a caller receives a general object but needs to ask whether it has one particular extra capability. A checked pointer conversion can answer that question without pretending every base object has the derived type.
#include <iostream>
class Item {
public:
virtual ~Item() = default;
};
class Audio : public Item {
public:
int minutes() const { return 15; }
};
int main() {
Audio clip;
Item* item = &clip;
Audio* audio = dynamic_cast<Audio*>(item);
if (audio != nullptr) std::cout << audio->minutes() << '\n';
}
dynamic_cast<Audio*> asks for a checked pointer to the derived type. The base must be polymorphic, meaning it has at least one virtual function; the virtual destructor satisfies that requirement here. If the actual object is not an appropriate Audio, the pointer form returns nullptr. Check that result before using -> or dereferencing it.
This does not create an object or transfer ownership. The pointer still refers to the original object, whose lifetime must cover the access. Preserve read-only access by converting a const Base* to a const Derived*. We use only pointer casts in this lesson; the failure path is an ordinary null result.
The editor supplies a helper that receives const Publication*. A Magazine has an issue number that the base does not promise. Replace the safe null placeholder with a checked cast. Leave the following null guard in place. A pointer to an ordinary Publication cannot provide a magazine issue, and a null input points to no object at all. Both should take that guard and return zero; only a successful cast should reach magazine->issue(). Prefer virtual operations when the capability really belongs in the common interface.
Edit main.cpp; the supplied Console probes already call your code.
dynamic_cast<const Magazine*>(publication) to initialize magazine, keeping the null guard. Expect issue 7 for the magazine and 0 for both the ordinary and null pointers.Use Run to inspect the Console, then Submit to check your work.