sv_jan5
sv_jan5

Reputation: 1573

Dynamic stack data type declaration in c++

Is it possible to do the following:

dtype            //contains data type information  
stack<dtype> st; // stack declartion

I want to dynamically decide the type of stack. Is it possible to do this in c++?

Upvotes: 0

Views: 305

Answers (1)

dmi
dmi

Reputation: 1479

Yes it is possible. You can use the polimorphism for this reason and keep a pointer to the base class as the argument of the stak's template. Then runtime you can decide what type object to allocate. Important is that it shall be derived from the base class.

class Object;
class A : public Object;
class B : public Object;
std::stack<Object*> buf;
if (...)
{
   buf.push(new A);
} else
{
   buf.push(new B);
}

Upvotes: 2

Related Questions