2

The codes comprises 1 header file and 1 source file. I have cut the irrelevent codes and still maintain the compilation error.

Huffman.h

#ifndef HUFFMAN
#define HUFFMAN
template<int size>
class Huffman{
protected:
    int code_len[size];
    int code[size];
    void genCode(){
    }
};
template<int size>
class HuffmanEncode :public Huffman<size>{
public:
    void f(){
        for (int i = 0; i < size; i++){
            code_len[i] = 0;
        }
    }
};
#endif

main.cpp

#include"Huffman.h"
int main()
{
    HuffmanEncode<256> h;
}

The member variable code_len is defined in the base class. I don't know why it said code_len is undefined.

songyuanyao
  • 169,198
  • 16
  • 310
  • 405
zbh2047
  • 393
  • 1
  • 9
  • 2
    Try `this->code_len[i] = 0;` I am sure there is a duplicate for this. – drescherjm Dec 11 '18 at 02:19
  • 4
    I don't think this deserves so many downvotes. It's not at all obvious, and not that easy to find duplicates without already knowing the cause. – John Ilacqua Dec 11 '18 at 02:23
  • See https://stackoverflow.com/questions/4643074/why-do-i-have-to-access-template-base-class-members-through-the-this-pointer – francesco Dec 11 '18 at 02:53

1 Answers1

3

This is a special case for templates. The problem is that the nondependent name code_len won't be looked up in the scope of dependent base class Huffman (which depends on template parameter size).

You could make the name code_len dependent, then it will be looked up only at the time of instantiation; at that time the template argument has been known and the base class has been instantiated, then the name code_len could be found at the scope of base class (like non-template base class). e.g.

this->code_len[i] = 0;

or

Huffman<size>::code_len[i] = 0;
songyuanyao
  • 169,198
  • 16
  • 310
  • 405
  • I think you should make it clearer in the answer that the reason specifically is because the base class is a template where the template parameter depends on the derived class's template parameter. – John Ilacqua Dec 11 '18 at 02:33