Tuesday 12 June, 2007

Conceptual "Virtual Constructors"

In one of my old article I had said that we cannot make the constructors virtual.

But its possible to have Conceptual Conceptual "Virtual Constructors". You might be wondering what do I mean by conceptual here?

Consider following code snippet,


class CAccountIface
{

};

class CSavingsAccount : public CAccountIface
{

};

class CCreditAccount : public CAccountIface
{

};

 


And I have one more class which will have a list of accounts


class CBank
{
    public:
        CAccountIface* CreateAccount(int iAccType);
        std::vector<CAccountIface *> m_Accounts;
}


 Here the member function CAccountIface* CBank:: CreateAccount(int iAccType) acts like a virtual constructor. Depending on the type the user passes either the constructor for CSavingsAccount or CCreditAccount will be called and respective object will be instantiated. This behaves like a virtual constructor.


We can even establish virtualism in case of copy constructors.

Let's try writing a copy c'tor for CBank class.


CBank::CBank(const CBank &AnotherBank)
{

    for(std::vector<CAccountIface *>::size_type i = 0; i < AnotherBank.m_Accounts.size(); ++i )
    {
        this->m_Accounts[i] = AnotherBank.m_Accounts[i]->Clone();
    }
}


I guess u'll already be wondering about the implementation for clone() member function.

Clone() has to be a pure virtual function in CAccountIface, and we can override this in CSavingsAccount and CCreditAccount to clone itself.

So the updated code will be as shown below,


class CAccountIface
{
    public:
        virtual CAccountIface *Clone() = 0;
};

class CSavingsAccount : public CAccountIface
{
    public:
        virtual CSavingsAccount *Clone(){ return new CSavingsAccount(*this);}

};

class CCreditAccount : public CAccountIface
{
    public:
        virtual CCreditAccount *Clone(){ return new CCreditAccount(*this);}

};


When we say


m_Accounts[i]->Clone();


The Clone() function will be called based on the type of object pointed by the pointer m_Accounts[i].

This concept is also referred to as "Factory Pattern"

No comments: