The Fugue

Counterpoint by Hans Fugal

Constructors, coercion and casting, oh my!

Posted by Hans Fugal Mon, 05 Jun 2006 19:08:18 GMT

This little bit of C++ trivia I may have known once but had forgotten. If you have the appropriate constructor, the compiler will happily coerce for you:

class Foo
{
public:
Foo(int);
int i;
};

int bar(Foo f) 
{
return f.i;
}

int main(void)
{
return bar(42);
}

You can also explicitly cast, which is useful when you are feeling explicit, or want to cast to a subclass for polymorphic reasons.

no comments | Tags , , | atom

Comments

Leave a response

Leave a comment