P
P
Pavel2019-01-28 22:25:45
C++ / C#
Pavel, 2019-01-28 22:25:45

I created a class in a pure C++ project, but when I try to allocate memory for it in main, I catch an unresolved external symbol. Why?

header file

#pragma once
template <typename T>
class Tree
{
public:
  Tree();
  ~Tree();
};

cpp file
#include "pch.h"
#include "Tree.h"


template <typename T>
Tree<T>::Tree()
{
}


template <typename T>
Tree<T>::~Tree()
{
}

main
int main()
{
  auto tvar = new Tree<int>;
    std::cout << "Hello World!\n"; 
}

If I transfer the implementation of the constructor and destructor to the header, everything works.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
J
jcmvbkbc, 2019-01-28
@youkerni

cpp file
template <typename T>
Tree<T>::Tree()
{
}

How do you think the compiler will know when compiling this cpp file that you want to work with Tree<int>in some other file?
Only if you make an explicit instantiation of the types you need in the same translation unit. Otherwise the object file resulting from copying this cpp file will be (almost) empty.
...and this is a typical solution to this problem.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question