Thursday, May 10, 2018

Vector of Smart Pointers (revised)

The previous example doesn't really show the polymorphism. This example shows the coolness of C++ (version 14):





#include <iostream>
#include <vector>
#include <memory>


// Require C++ version 14 to compile!

class Base
{
public:
    Base(Base & other);
    Base(Base *);
    Base(char const * const tag, char const * const desc) : m_tag(tag), m_desc(desc) {}
    ~Base() = default;

    void print();
    virtual void Process(); 

public:
    std::string m_tag = "";
    std::string m_desc = "";
};



Base::Base(Base & rhs)
{
    m_tag = rhs.m_tag;
    m_desc = rhs.m_desc;
}


Base::Base(Base *pOther)
{
    m_tag = pOther->m_tag;
    m_desc = pOther->m_desc;
}


void Base::print()
{
    std::cout << __FUNCTION__ << "(" << this << "): Base::m_tag = " << m_tag << std::endl 
              << "                  Base::m_desc = " << m_desc << std::endl;
}


void Base::Process()
{
    std::cout << __PRETTY_FUNCTION__ << std::endl;
}



template <class CNAME>
Base* createClass(char const *const tag, char const * const desc)
{
    CNAME * pObj  = new CNAME(tag,desc);

    std::cout << "Inside " << __FUNCTION__  << "(): ";
    pObj->Process();
    return dynamic_cast<Base*>(pObj);
}


template <class CNAME>
std::unique_ptr<Base> createUniqueClass(char const *const tag, char const *const desc)
{
    std::unique_ptr<Base> obj(createClass<CNAME>(tag, desc));
    return obj;
}



class KelasA : public Base
{
public:

    KelasA(char const * const tag, char const * const desc) : Base(tag, desc) {}
    void Process() override;
};


void KelasA::Process()
{
    std::cout << __PRETTY_FUNCTION__ << std::endl;
}


class KelasB : public Base
{
public:
    KelasB(char const * const tag, char const * const desc) : Base("B", desc) {}
    void Process() override;
};



void KelasB::Process()
{
    std::cout << __PRETTY_FUNCTION__ << std::endl;
}




int main()
{
    std::vector<std::unique_ptr<Base>> vb;

    vb.push_back(createUniqueClass<KelasA>("A", "Kelase A-1"));

    vb.push_back(createUniqueClass<KelasB>("B", "Kelase B-1"));

    //for(auto v = vb.begin(); v != vb.end(); v++)a
    for(auto & v : vb)
    {
        v->Process();
        v->print();
    }

    return 0;
}

No comments:

Post a Comment