Link to home
Start Free TrialLog in
Avatar of MichaelMaromm
MichaelMaromm

asked on

Template derivation

Hi,

I created a template class :

template<class T>
class CBaseT
{
 T *m_pT;
public :
 CBase();
 ~CBase();
 T *Get();
 void Set(T *pT);
};

And I derived a class from it :

class Derived : public CBaseT<char>
{
 public :
 Derived() {Set("A");} // Correction, instead of: Set('A');
 ~Derived();
};

The problem is that I got a link error which says that
the class CBaseT<char> is not found.

My question is : Why is that happened , and how can I
fix it that CBaseT<char> will be found ?

 Thanks
 Michael
Avatar of IainHere
IainHere

Set('A') passes a const char, but your definition of Set() requires a char*.

You could change the definition to

void Set(T pT);

and it should work.
Or you could simply pass in "A" instead of 'A'.
"A" will be a char * because it creates a string of two characters (A and \0) whereas 'A' is just one char.
ASKER CERTIFIED SOLUTION
Avatar of Axter
Axter
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Continuation:

Although the current C++ standards say that you can put the functions in the *.cpp file, most compilers do not support this capability.

If you put the code in the *.cpp file, then only code that includes the *.cpp file can declare new types of your template class.

An alternative to this is to put a special forward declaration for each type that you will use for the template class.

The syntax for this is the following:

template CBaseT<char>;

The above forward declaration would be put into the *.cpp file that has your template function defined.
You would have to do this for each type if you want to use this method.

I do not recommend using the above method unless you really have a good reason for keeping the template function definition inside your *.cpp file.

It is far easier to just keep the template function difinition in the *.h header file, and this is the common method used by most programmers for template classes.
Avatar of MichaelMaromm

ASKER

Thank you Axter,
You realy helped me.

Michael