Search code examples
c++abstract-classderived-class

New derived class from abstract classes


I have encountered a problem with creating new class objects.

The abstract class is called SimpleList, currently doesn't do anything on its own.

template<class T>
class SimpleList {

public:
    string ListName;    

    SimpleList(){
    };
    string getName(){
        return ListName;
    };
};

template<class T> 
class Queue : public SimpleList<T> {

public:
    string ListName;    

    Queue(string& name){
        ListName = name;
    }   

    string getName(){
        return ListName;
    }
};

And here is where I am attempting to assign 'pQLi' to a new Queue, where Queue is a derived class.

SimpleList<int> *pQLi;

if (indicator == 'i' ){
    pQLi = new Queue<int>(name1);

}

But whatever I do to print out the name of pQLi (or access any data from it, but in the simplest case ) outside of the Queue, only ' ' is coming out. For example, if I do this

cout <<(*pQLi).getName() <<"\n";

Instead of printing out the ListName, a blank character comes out


Solution

  • its as simple as it is. Make your base class getName() virtual as follows. Since you are care of the content of pointer, you need a late binding of the object.

    template<class T>
    class SimpleList
    {
    public:
        string ListName;
    
        SimpleList() = default;
        virtual string getName(){
            return ListName;
        };
    };
    

    However, I do not understand, why you need a template class for this. You have not used the type(T) anywhere. And try to use initializer_list whenever possible and smart pointers are good to use in following cases. I have made a small correction as follows. Hope this has answered your question.

    #include <iostream>
    
    template<class T>
    class SimpleList
    {
    private:
        std::string ListName;
    public:
        SimpleList() = default;
        virtual ~SimpleList(){}
        virtual const std::string& getName()const
        {   return ListName;    };
    };
    
    template<class T>
    class Queue : public SimpleList<T>
    {
    private:
        std::string ListName;
    public:
        Queue(const std::string& name)
            :ListName(name) {}
    
        const std::string& getName()const
        {   return ListName;    }
    };
    
    int main()
    {
        SimpleList<int> *pQLi;
    
        char indicator = 'i';
        std::string name1 = "nothing";
    
        if (indicator == 'i' ){
        pQLi = new Queue<int>(name1);}
    
        std::cout <<(*pQLi).getName() <<"\n";
    
        delete pQLi;
        pQLi = nullptr;
        return 0;
    }