Automatic type conversion.

J

Jason Heyes

I want Foo-type objects to be convertible to Bar-type objects. Can I use
operator Bar() to do this just as I would use operator bool() to convert to
boolean? Example:

class Foo
{
public:
operator Bar() const;
};

Thanks.
 
A

Alf P. Steinbach

* Jason Heyes:
I want Foo-type objects to be convertible to Bar-type objects. Can I use
operator Bar() to do this just as I would use operator bool() to convert to
boolean?

Yes.
 
R

Rolf Magnus

Jason said:
I want Foo-type objects to be convertible to Bar-type objects. Can I use
operator Bar() to do this just as I would use operator bool() to convert
to boolean? Example:

class Foo
{
public:
operator Bar() const;
};

Yes, you can use that. But it is usually better to make a conversion
constructor in Bar, like:

class Bar
{
public:
Bar(const Foo& rhs);
};
 
J

Jonathan Mcdougall

I want Foo-type objects to be convertible to Bar-type objects. Can I use
operator Bar() to do this just as I would use operator bool() to convert to
boolean? Example:

class Foo
{
public:
operator Bar() const;
};

(mmm.. why not just try it?)

Yes you can, but be aware that automatic conversions have their pitfalls
and you may get some surprising results. Automatic conversions reduces
the number of places a compiler can warn against potential logic errors.


Jonathan
 
P

Peter Koch Larsen

Rolf Magnus said:
Yes, you can use that. But it is usually better to make a conversion
constructor in Bar, like:

class Bar
{
public:
Bar(const Foo& rhs);
};
.... and even better to make it explicit (if this is compatible with Jasons
goal):

explicit Bar(const Foo& rhs);

/Peter
 

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,756
Messages
2,569,534
Members
45,007
Latest member
OrderFitnessKetoCapsules

Latest Threads

Top