Search code examples
c++templatesabstract-data-type

Will not create a class template for c++


I am trying to figure out how to use classes with class template and I get these errors:

Error 1 error LNK2019: unresolved external symbol "public: __thiscall AdtBag::AdtBag(void)" (??0?$AdtBag@H@@QAE@XZ) referenced in function _main C:\Users\User\Documents\Visual Studio 2013\Projects\ADTBagAddition\ADTBagAddition\Source.obj ADTBagAddition

Error 2 error LNK2019: unresolved external symbol "public: __thiscall AdtBag::~AdtBag(void)" (??1?$AdtBag@H@@QAE@XZ) referenced in function _main C:\Users\User\Documents\Visual Studio 2013\Projects\ADTBagAddition\ADTBagAddition\Source.obj ADTBagAddition

Error 3 error LNK2019: unresolved external symbol "public: void __thiscall AdtBag::store_in_bag(int)" (?store_in_bag@?$AdtBag@H@@QAEXH@Z) referenced in function _main C:\Users\User\Documents\Visual Studio 2013\Projects\ADTBagAddition\ADTBagAddition\Source.obj ADTBagAddition

Error 4 error LNK2019: unresolved external symbol "public: int __thiscall AdtBag::whats_in_bag(void)" (?whats_in_bag@?$AdtBag@H@@QAEHXZ) referenced in function _main C:\Users\User\Documents\Visual Studio 2013\Projects\ADTBagAddition\ADTBagAddition\Source.obj ADTBagAddition

Error 5 error LNK1120: 4 unresolved externals C:\Users\User\Documents\Visual Studio 2013\Projects\ADTBagAddition\Debug\ADTBagAddition.exe ADTBagAddition

Here is my code:

source.cpp

#include <iostream>
#include "AdtBag.h"

using namespace std;

int main () {
    AdtBag<int> BagInt;
    int a = 78;
    cout << "Int Bag Contains: " << endl;
    BagInt.store_in_bag ( a );
    cout << BagInt.whats_in_bag () << endl;

    return 0;
}

AdtBag.h

#ifndef __ADTBAG__
#define __ADTBAG__

template<class ItemType>
class AdtBag {
private:
    ItemType in_bag;
public:
    AdtBag<ItemType> ();
    ~AdtBag<ItemType> ();

    void store_in_bag ( ItemType into_bag );
    ItemType whats_in_bag ();
};

#endif

AdtBag.cpp

#include "AdtBag.h"

template <class ItemType>
AdtBag<ItemType>::AdtBag () {
}

template <class ItemType>
AdtBag<ItemType>::~AdtBag () {
}

template<class ItemType>
void AdtBag<ItemType>::store_in_bag ( ItemType into_bag ) {
    in_bag = into_bag;
}

template<class ItemType>
ItemType AdtBag<ItemType>::whats_in_bag () {
    return in_bag;
}

Why is this producing the error messages? I'm using Visual Studio 2013 if that matters. I thought I did everything correctly, but I guess not. Any suggestions?


Solution

  • Loosely speaking, all template class code must be in the header.

    Essentially, this is because template code is only compiled when a template is instantiated for some type.