Hi,
How can I define template formal parameter as T*?

I read in some textbook that if I define template with formal parameter T* then
actual parameter can be of the type T1*,provided that T1 is derived from T

Thank you in advance

You must be thinking about polymorphism.

Yes we are.
Could you help us out?

Here is an example :

#include<iostream>

using namespace std;

template<typename T>
class Base
{
private:
	T* x;
public:
	Base() {
		x = new T[1]; 
		x = false;
		cout<<"Base created\n"; 
	
	}
	Base(T l) {
		cout<<"Base created\n";
		x = new T[1];
		x = l;
	}

	T X() { return x; }
	void X(T y) { x  = y; }

	virtual ~Base(){ delete [] x; cout<<"Base destroyed\n";}
};

template<typename T>
class Derived : public Base<T>
{
private:
	T* y;
public:
	Derived() : Base()
	{
		cout<<"Derived created\n"; 
		y = new T[1];		
	}
	Derived(T x0, T y0) : Base(x0)
	{
		cout<<"Derived created\n";
		y = new T[1];
		y = y0;
	}

	~Derived() { delete [] y;  cout<<"Derived destroyed\n";}
};

int main()
{
	Base<bool> * base1 = new Base<bool>; //baseobj created
	Base<bool> * base2; 
	
	Derived<bool> der1; //derived obj created
	
	//polymorphism
	base2 = &der1; //ordinary

	base2 = dynamic_cast<Base<bool>*>(&der1); //safer
	if(!base2)
		cout<<"cannot convert\n";

	delete [] base1;
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.