Smart pointers and inheritance

  • Thread starter =?iso-8859-1?q?Ernesto_Basc=F3n?=
  • Start date
?

=?iso-8859-1?q?Ernesto_Basc=F3n?=

Hi everybody:

I have implemented a Ptr<T> template class that I want to use in my
framework.

Let's say I have:

template <class T>
class Ptr<T>;

class A;
class B : public A;

class C
{
public:
...
int GetValue(Ptr<A> val);
};


I want to instance my objects using my smart pointer:

Ptr<B> b(new B());

If I would use a standard pointer, the calling to int GetValue(A* val);
would be:

c->GetValue(b); //valid using standard pointers

but it does not compile using my notation because there is no match
between

Ptr<A> and Ptr<B>.

How can I implement my smart pointer to be able to call

c->GetValue(b);

using my smart pointers?

Regards,


Ernesto
 
M

Markus Moll

Hi
Hi everybody:

I have implemented a Ptr<T> template class that I want to use in my
framework. [...]
Ptr<B> b(new B());

If I would use a standard pointer, the calling to int GetValue(A* val);
would be:

c->GetValue(b); //valid using standard pointers

but it does not compile using my notation because there is no match
between

Ptr<A> and Ptr<B>.

The usual way is to add a templated constructor that takes a smart-pointer
to any other type U and let the compiler find out if the conversion from U*
to T* is legal:

template<typeame U> Ptr<T>(Ptr<U> other)
: pointer(other.pointer), // this only compiles if there is a conversion
from U* to T*!
counter(other.counter) // assuming external reference count
{
inc(counter);
}

Markus
 
O

Ondra Holub

Ernesto Bascón napsal:
Hi everybody:

I have implemented a Ptr<T> template class that I want to use in my
framework.

Let's say I have:

template <class T>
class Ptr<T>;

class A;
class B : public A;

class C
{
public:
...
int GetValue(Ptr<A> val);
};


I want to instance my objects using my smart pointer:

Ptr<B> b(new B());
 
S

Salt_Peter

Ernesto said:
Hi everybody:

I have implemented a Ptr<T> template class that I want to use in my
framework.

Let's say I have:

template <class T>
class Ptr<T>;

class A;
class B : public A;

class C
{
public:
...
int GetValue(Ptr<A> val);
};


I want to instance my objects using my smart pointer:

Ptr<B> b(new B());
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top