0

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

3
Contributors
3
Replies
4
Views
8 Years
Discussion Span
Last Post by firstPerson
0

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;
}
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.