Tom Tom
Tom Tom

Reputation: 1209

Changing Destructor order

I need in destruction of a class that first the destructor of members are called before the class itself. I know the destruction order are normally in the reverse order. But I nedd this in special case.

// PortA
class PortA
{
public:
    PortA()     { cout << " PortA\n"; }
    ~PortA()    { cout << " ~PortA\n"; }
};

// PortB
class PortB
{
public:
    PortB()     { cout << " PortB\n"; }
    ~PortB()    { cout << " ~PortB\n"; }
};


class Card
{
public:
    Card()      { cout << "card\n"; }
    ~Card()     { cout << "~card\n"; }


    PortA mPA;
    PortB mPB;
};

That produces :

 PortA
 PortB
card
~card
 ~PortB
 ~PortA

But I need in this case:

card
 PortA
 PortB
 ~PortB
 ~PortA
~card

Closse first the port before the card itself.

Upvotes: 1

Views: 1162

Answers (3)

Yuriy Ivaskevych
Yuriy Ivaskevych

Reputation: 966

Consider manipulate them explicitly, for example:

class Card
{
public:
    Card()      
    {
        cout << "card\n";
        mPA = new PortA;
        mPB = new PortB;
    }

    ~Card()     
    {
        delete mPB;
        delete mPA;
        cout << "~card\n"; 
    }


    PortA *mPA = nullptr;
    PortB *mPB = nullptr;
};

Now if you write something like this:

{
    Card c;
}

you'll get what you want.

Upvotes: 1

Israel Unterman
Israel Unterman

Reputation: 13510

What I would do is a robust and explicit destruction.

I would define a destroy() method in the ports, and then would call them from within the destructor of card.

Upvotes: 1

Quentin
Quentin

Reputation: 63114

Adding a base class to Card:

class BaseCard {
public:
    BaseCard()  { std::cout << "basecard\n"; }
    ~BaseCard() { std::cout << "~basecard\n"; }
};

class Card : BaseCard
{
public:
    Card()      { std::cout << "card\n"; }
    ~Card()     { std::cout << "~card\n"; }


    PortA mPA;
    PortB mPB;
};

Has BaseCard's constructor and destructor called when you need:

basecard
 PortA
 PortB
card
~card
 ~PortB
 ~PortA
~basecard

Alternatively, you could lift PortA and PortB out of Card and lay all three as members inside a wrapper:

class CardWrapper {
    Card card;
    PortA mPA;
    PortB mPB;
};

Upvotes: 2

Related Questions