I am trying to use std::shared_ptr, but i am not sure if i can use shared_ptr for a abstract class and call a derived class from this smart pointer. Here is the code that i have at present
IExecute *ppCIExecuteExecuteOperation = NULL;
for(int i = 0; i < 3; ++i)
{
    switch (stOperationType.key)
    {
        case E_OPERATIONKEY::DrawCircle:
        pCIExecuteExecuteOperation = new CCircle();
        break;
        case E_OPERATIONKEY::DrawSquare:
        pCIExecuteExecuteOperation = new CSquare();
        break;
        case E_OPERATIONKEY::Rhombus:
        pCIExecuteExecuteOperation = new CRehombus();
        break;
        default:
        break;
    }
} 
pCIExecuteExecuteOperation->Draw();
Here IExecute is a abstract class and CCircle, CSquare, CRhombus is a derived class of IExecute.
All I want to do is use shared_ptr<IEXectue>pCIExecuteExecuteOperation(nullptr)
and inside a switch statement make it point to one of the derived class, How can i achieve this?
Edit: The answers were to use make_shared or reset()
Thanks guys, I dint expect it to be so easy.
That's easy. Look at code and feel.
std::shared_ptr<IExecute> ppCIExecuteExecuteOperation;
for(int i = 0; i < 3; ++i)
{
    switch (stOperationType.key)
    {
        case E_OPERATIONKEY::DrawCircle:
            pCIExecuteExecuteOperation.reset(new CCircle());
            break;
        case E_OPERATIONKEY::DrawSquare:
            pCIExecuteExecuteOperation.reset(new CSquare());
            break;
        case E_OPERATIONKEY::Rhombus:
            pCIExecuteExecuteOperation.reset(new CRehombus());
            break;
        default:
            break;
    }
} 
pCIExecuteExecuteOperation->Draw();
The line
IExecute *ppCIExecuteExecuteOperation = NULL;
should be replace with
std::shared_ptr<IExecute> pExecute;
and then each of the lines with assignments can be written as
pExecute.reset(new CCircle);
Then you can call Draw
pExecute->Draw();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With