Created
September 17, 2020 22:13
-
-
Save blogdarkspot/2b0eda0c6e5308ea46c48860096416b5 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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