C++ Memory::static_pointer_cast
In addition to upcasts (from pointer-to-derived to pointer-to-base), static_cast can also execute downcasts between pointers to related classes (from pointer-to-base to pointer-to-derived). No verifications are made at runtime to ensure that the object being converted is actually a full object of the target type. So, it is the responsibility of the programmer to guarantee the security of the conversion.
Syntax
Following is the syntax for C++ Memory::static_pointer_cast −
shared_ptr<T> static_pointer_cast (const shared_ptr<U>& sp) noexcept;
Parameters
sp − Its a shared pointer.
Example 1
Following is the example, where we are going to perform static_pointer_casting and getting the output.
#include <iostream>
#include <memory>
struct TP {
static const char* static_type;
};
const char* TP::static_type = "TUTORIALSPOINT";
int main (){
std::shared_ptr<TP> Result;
Result = std::make_shared<TP>();
std::cout << "Result: " << Result->static_type << '\n';
return 0;
}
Output
Let us compile and run the above program, this will produce the following result −
Result: TUTORIALSPOINT
Example 2
Let's look into the following example, where the static_pointer_cast go up a class hierarchy.
#include <iostream>
#include <memory>
class Base{
public:
int x;
virtual void tp() const{
std::cout << "HELLO\n";
}
virtual ~Base() {}
};
class Derived : public Base{
public:
void tp() const override{
std::cout << "Namaste\n";
}
~Derived() {}
};
int main(){
auto basePtr = std::make_shared<Base>();
std::cout << "A Says: ";
basePtr->tp();
auto derivedPtr = std::make_shared<Derived>();
std::cout << "B Says: ";
derivedPtr->tp();
basePtr = std::static_pointer_cast<Base>(derivedPtr);
std::cout << "C Says: ";
basePtr->tp();
}
Output
On running the above code, it will display the output as shown below −
A Says: HELLO B Says: Namaste C Says: Namaste
Example 3
Considering the following example where we are going to construct a temporary shared_ptr and calling an operator.
#include <iostream>
#include <memory>
struct BaseClass {};
struct DerivedClass : BaseClass {
void x() const{
std::cout << "WELCOME TO TP\n";
}
};
int main(){
std::shared_ptr<BaseClass> ptr_to_base(std::make_shared<DerivedClass>());
std::static_pointer_cast<DerivedClass>(ptr_to_base)->x();
}
Output
when the code gets executed, it will generate the output as shown below −
WELCOME TO TP