Skip to content

Instantly share code, notes, and snippets.

@blogdarkspot
Created September 17, 2020 22:13
Show Gist options
  • Save blogdarkspot/2b0eda0c6e5308ea46c48860096416b5 to your computer and use it in GitHub Desktop.
Save blogdarkspot/2b0eda0c6e5308ea46c48860096416b5 to your computer and use it in GitHub Desktop.
#include <iostream>
#include <memory>
struct Base : public std::enable_shared_from_this<Base>
{
int a;
virtual void f() const { std::cout << "I am base!\n"; }
virtual ~Base() {}
};
struct Derived : public Base
{
void f() const override
{
std::cout << "I am derived!\n";
}
void x() const
{
auto self = std::static_pointer_cast<Derived>(shared_from_this());
auto lambda = [self]() { self->y(); };
self->f();
}
void y()
{
std::cout << "new function" << std::endl;
}
~Derived() {}
};
int main() {
auto basePtr = std::make_shared<Derived>();
basePtr->x();
// basePtr->f();
//auto downcastedPtr = std::static_pointer_cast<Derived>(basePtr);
//downcastedPtr->f();
// downcastedPtr->x();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment