inherit class template?
Jul 20, 2008 at 12:53pm Jul 20, 2008 at 12:53pm UTC
Btw, is there any tips to inherit class template?
I''m a little confusing on it.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
template <typename T>class clsTemplate
{
public :
clsTemplate(T i)
{
//...
}
void test()
{
}
};
class clsChild : clsTemplate<char >
{
public :
clsChild(/* no parameters */ ) //??
{
//...
}
clsChild(char c) //??
{
//...
}
void test2()
{
test() //??
}
};
I've got a LOT of errors when compiling code like that. Any suggestion please?
Jul 20, 2008 at 6:15pm Jul 20, 2008 at 6:15pm UTC
I don't see anything horribly wrong, except that you aren't using public inheritance. (You should generally stick to public inheritance unless you know what you are doing...)
Here's how I tested it:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
#include <iostream>
using namespace std;
template <typename T>class clsTemplate
{
public :
T value;
clsTemplate(T i)
{
this ->value = i;
}
void test()
{
cout << value << endl;
}
};
class clsChild : public clsTemplate<char >
{
public :
clsChild(/* no parameters */ ): clsTemplate<char >( 0 ) // default char is NUL
{
;
}
clsChild(char c): clsTemplate<char >( c )
{
;
}
void test2()
{
test();
}
};
int main()
{
clsTemplate <int > a( 42 );
clsChild b( 'A' );
a.test(); // should print "42"
b.test(); // should print "A"
b.test2(); // should print "A"
return 0;
}
When you are constructing descendent classes, it is generally a good idea to initialize the ancestor class in the constructor's initializer list, even if that is the only thing you do:
1 2 3
clsChild():
clsTemplate <char > ( ' ' ) // default char is SPACE
{ }
Hope this helps.
Last edited on Jul 20, 2008 at 6:16pm Jul 20, 2008 at 6:16pm UTC
Jul 21, 2008 at 4:46am Jul 21, 2008 at 4:46am UTC
When you are constructing descendent classes, it is generally a good idea to initialize the ancestor class in the constructor's initializer list
It is applied to method/destructor too?
Jul 21, 2008 at 2:41pm Jul 21, 2008 at 2:41pm UTC
No. Base class destructors are automagically called -- you don't need to do anything but worry about destructing stuff that belongs to this class.
Hope this helps.
Jul 22, 2008 at 4:28am Jul 22, 2008 at 4:28am UTC
Thanks Duoas ^_^ ...!
Thank you.
Topic archived. No new replies allowed.