0

I'm trying to make a program that changes and compares fields of different documents. There is one base class with virtual functions and some children classes. For convenience I want to put objects of children classes into custom container that represents a linear stack. Here is the header code:

template <class T>

class DocContainer{
public:
    struct ListElement{ // the stack itself
        T obj;
        ListElement *next;
    };
    DocContainer();
    ~DocContainer();

    void pop_top();
    T &get_top() const;
    T &operator[](int);
    void push_top(const T &);
    int size() const;
    void clear();

private:
        ListElement *first;
        int num;
};

I tried to google how to actualize a container for objects of different types and found out that I'm supposed to contain pointers to parent class using the polymorphism. But when I try to use it like this:

Passport *pass = new Passport;
// some code
DocContainer<Document*> DC;
DC.push_top(dynamic_cast<Document*>(pass));

The compiler says:

undefined reference to `DocContainer::push_top(Document* const&)'

Along with the same warnings about constructor and destructor of container.

Class Passport is a child class of Document.

class Passport : public Document{
// some code
};

The push_top() function of container in .cpp file:

template <class T>
void DocContainer<T>::push_top(const T &A){ 
    auto cur = new ListElement;
    cur->obj = A;
    cur->next = first;
    first = cur;
    num++;
    delete cur;
}

There is something surely wrong, but I couldn't find any clear answer. What's the mistake? Thanks in advance

  • 3
    Not enough info, but it is a possible duplicate of [Why can templates only be implemented in the header file?](https://stackoverflow.com/questions/495021/why-can-templates-only-be-implemented-in-the-header-file) – Swift - Friday Pie Dec 17 '17 at 07:56
  • Its not clear in the question what either of `Passport` or `Document` is. Are they related types? Also, you haven't shown the implementation of `push_top` as, I think, @Swift is referring to. And you should update the question with the exact error message and the source that the error refers to. – quamrana Dec 17 '17 at 12:36
  • You don't need a dynamic_cast here (if you ever find yourself needing it, you are doing inheritance-based polymorphism wrong). – n. m. could be an AI Dec 17 '17 at 18:39
  • Also please consider using smart pointers instead of raw pointers. – n. m. could be an AI Dec 17 '17 at 18:45
  • @quamrana Passport is a child class and Document is a parent. I have updated the question with more details. I read the post above about implementation, but I still don't get how I should change my container – Augustus Grin Dec 17 '17 at 18:46
  • Your mistake is as @Swift has indicated. It’s the linker that is complaining, not the compiler. And you don’t need the cast, as the compiler has enough information to work out what’s needed. – quamrana Dec 17 '17 at 18:48

0 Answers0