C++ gotcha

I came across an amusing example in Meyers’ Effective STL Item 6***.

class Widget { ... };
Widget w();

As Meyers explains,  it seems like the default constructor is called. However, in C++ this second line is actually declaring a function ‘w’ that takes no parameters and returns a ‘Widget’. If the code author intended for the constructor to be called, he would have to write:

class Widget { ... };
Widget w;

I chuckled to myself after I saw this because the former will cause the Java compiler to get angry. This is another example of how you have to pay attention when you write C++.

*** I love Meyer’s works and his writing style.  He writes to you as a professional and an equal, even though he is a master.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s