Hai!

I tried writing a stack program using the concept of templates.
It worked well for the int,char and double.But when i tried to pass a complex class error occured.

Is it possibleto pass a class to the template class?
If so what is the syntax for doing it?

I have got the code attached with this mail please specify if any changes is to be made in it.


Urs,

PriyaJaiGanesh

Attachments
#include<iostream.h>
#include<conio.h>
const int SIZE = 10;
template <class StackType>
class Stack
{
private:
StackType stck[10];
int index;
public:
Stack()
{
index = 0;
}
/*Stack(complex &c1)
{
int real = c1.real;
int imag = c1.imag;
}*/

void push(StackType val);
StackType pop();
};

template <class StackType> void Stack<StackType>::push(StackType val)
{
if (index == SIZE)
{
cout<<"The Stack is Overflow"<<endl;
return;
}
stck[index] = val;
index++;
}

template <class StackType> StackType Stack<StackType>::pop()
{
if(index==0)
{
cout<<"The stack is empty"<<endl;
return 0;
}
index--;
return stck[index];
}

class complex
{
int real;
int imag;
public:
complex(int a,int b )
{
real = a;
imag = b;
}
void show()
{
cout<< real<<" +j "<<imag<<endl;
}
};

void main()
{
clrscr();
Stack<int> s1;
Stack<double> s2;
Stack<char> s3;
Stack<char *> s4;
Stack<complex> s5;
complex c1(1,2);
Stack< c1 >  s5;
cout<<"The Integer stack"<<endl;
s1.push(123);
s1.push(345);
s1.push(3);
cout<<s1.pop()<<endl;
cout<<s1.pop()<<endl<<endl;
cout<<"The Double stack"<<endl;
s2.push(10.11);
s2.push(11.2);
s2.push(1.1);
cout<<s2.pop()<<endl;
cout<<s2.pop()<<endl<<endl;
cout<<"The Character stack"<<endl;
s3.push('a');
s3.push('b');
s3.push('c');
cout<<s3.pop()<<endl;
cout<<s3.pop()<<endl<<endl;
cout<<"The String Stack"<<endl;
s4.push("Cat");
s4.push("Dog");
cout<<s4.pop()<<endl;
cout<<s4.pop()<<endl<<endl;
cout<<"The Complex number"<<endl;
s5.push(c1);
}

what error is it showing as the code looks fine to me

It shows that "default constructor for the stack<complex> is not found"

I tried adding the complex header file instead of the one i defined and surprisingly it worked correctly.

But still i want to know y it didn't work for my code or wat was wrong in my code.

Thank u so much for taking effort to clear my doubt.

urs,
PriyaJaiGanesh

OIC!! the complex class is being initialised with no params when you use it like that - so you need to code a default constructor (one with no parameters). This should be standard practice but try adding:

/* INSIDE the complex class */

complex(void)
{
    real = imag = 0;
}

This means when you use complex as a type/cast it will set real and imag to zero until you do anything with it - which wont matter in your case. Try the code.

This question has already been answered. Start a new discussion instead.