Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Invoking constructor in template class

Status
Not open for further replies.

raydona

Programmer
May 12, 2005
27
GB
I have created a template storage class which contains the following function:

template<class X>
void Queue<X>::insert(X& q)
{ X* p = new X(q);
.
.
}

By invoking the copy constructor in the class plugged in for X the storage class stores an exact copy of the object passed as an argument. (This is for programming reasons.) It works fine if what is plugged in for X is an object. But if a base class pointer is plugged in there is an error; memory is allocated but no type of constructor is invoked so that if I try to access the stored object the program crashes. I have defined constructors in the base and derived classes that take a pointer as an argument but those functios are never invoked. How can I force some type of constructor to be invoked when the template argument happens to be a base class pointer.

I would be grateful for all help.
 
If X is a pointer, you'll have to deference the pointer first, otherwise you'll just be copying the pointer, not the object it's pointing to.

If the object you're copying has pointer or reference member variables and doesn't have an appropriate copy constructor defined, you'll run into the same problem (i.e. a shallow copy).

I think the best you can do is just document some restrictions on what kind of object X has to be...
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top