Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::shared_ptr of abstract class to instantiate derived class [closed]

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.

like image 909
Barry Avatar asked Oct 27 '25 09:10

Barry


2 Answers

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();
like image 71
ikh Avatar answered Oct 29 '25 23:10

ikh


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();
like image 33
Wojtek Surowka Avatar answered Oct 29 '25 22:10

Wojtek Surowka