Inheritance and template in C++: Why doesn't the following piece of code compile? -


i have simple c++ program , not able compile , although tried search in google , try read template , inheritance , vector , didn't got clue mistake doing, can please me!! following code:

template <class t> class base {   public:   int entries; }; template <class t> class derive : public base<t *> {   public:   int j;   void pankaj(){j = entries;}   void clear();  }; template <class t> void derive<t>::clear() {   int i;   int j=entries; }; int main() {   derive b1; } 

and getting following error: pankajkk> g++ sample.cpp

sample.cpp: in member function 'void derive<t>::pankaj()': sample.cpp:14: error: 'entries' not declared in scope sample.cpp: in member function 'void derive<t>::clear()': sample.cpp:22: error: 'entries' not declared in scope sample.cpp: in function 'int main()': sample.cpp:26: error: missing template arguments before 'b1' sample.cpp:26: error: expected `;' before 'b1' 

thanks!!

you must use this->foo access member variable foo in template base classes. you may ask why.

also, old fox explains, must specify type t when declare variable b1.

template <class t> class base {   public:   int entries; };  template <class t> class derive : public base<t *> {   public:   int j;   void pankaj(){j = this->entries;}   void clear(); };  template <class t> void derive<t>::clear() {   int i;   int j=this->entries; };  int main() {   derive<int> b1; } 

live demo here


Comments

Popular posts from this blog

asp.net mvc - SSO between MVCForum and Umbraco7 -

Python Tkinter keyboard using bind -

ubuntu - Selenium Node Not Connecting to Hub, Not Opening Port -