In C++ the static and dynamic type of an object pointed to can differ.
Your static type of what the shared pointers in that vec point to is Account
.
The dynamic type of what the shared pointers in that vec point to varies. In your case, you put a Businessaccount
in it.
When you want to access or call methods, you are given access to only the static type methods.
The static type is what you have proven to the compiler the type contains at that line.
If you know better, you can do a static_cast<Businessaccount*>(vec.at(0).get())->getx()
. By doing so you are promising to the compiler that you have certain knowledge that the data at that location is actually a Businessaccount
. If you are wrong, your program's behavior is undefined (if you are lucky you get a crash).
You can also use RTTI (run time type information) to ask if a particular object is a particular sub-type (in some cases, where the base class has a virtual method).
Account* paccount = vec.at(0).get();
Businessaccount* pba = dynamic_cast<Businessaccount*>(paccount);
if (pba)
pba->getx();
the above checks if the paccount
is actually a Businessaccount*
, and if so calls getx
on it. If not, it does nothing.
Often dynamic casting is a sign you didn't design your object use properly; having to drill down past the interface into which implementation means maybe your interface wasn't rich enough.
In some scripting and bytecode compiled languages, they let you go off and call getx
and proceed to crash/throw an exception/etc if that method isn't isn't there.
C++ instead lets you use what you have claimed to be there (via the type system), then lets you write your own handler if you want dynamic type checking.