Note that there are some explanatory texts on larger screens.

plurals
  1. POdifference in two ways of declaring a class instance
    primarykey
    data
    text
    <p>Assume we have a class with no default constructor:</p> <pre><code>class Foo { public: Foo(int data) : _data(data) { } int data(void) const { return _data; } private: int _data; }; </code></pre> <p>Why does this compile and what does it do:</p> <pre><code>Foo x(); </code></pre> <p>Even though the above compiles, you can't do any of the following:</p> <pre><code>x.data(); // doesn't compile: request for member 'data' in 'x', which is of non-class type 'Foo()' x-&gt;data(); // doesn't compile: request for member 'data' in 'x', which is of non-class type 'Foo()' x().data(); // compiles!!! but linking fails with: undefined reference to `x()' x()-&gt;data();// doesn't compile: base operand of '-&gt;' has non-pointer type 'Foo' </code></pre> <p>I guess I'm just confused about what adding the () after the x does, and why the language allows this? Is this every allowable and/or useful? It seems that no Foo instance is allocated on the stack either, because even with -Wunused-variable, no warning occurs about the x in <code>Foo x();</code></p> <p>In contrast, both of the following do not compile:</p> <pre><code>Foo *x = new Foo; // error: no matching function for call to 'Foo::Foo() Foo *y = new Foo();// error: no matching function for call to 'Foo::Foo() </code></pre> <p>This seems more consistent, I don't understand what is going on with <code>Foo x();</code></p> <p>EDIT: Ok, figured it out. <code>Foo x()</code>; is a prototype for a function 'x', which takes no parameters and returns a Foo. Since the function isn't defined anywhere, trying to use it like a Foo instance (<code>x.data()</code>) or Foo pointer (<code>x-&gt;data()</code>) don't work. <code>x()-&gt;data()</code> doesn't work because <code>x()</code> is of type <code>Foo</code>, not pointer to <code>Foo</code>. <code>x().data()</code> compiles because <code>x()</code> returns <code>Foo</code>, which has a <code>data</code> method, but it fails to link because the function <code>x</code> has not been defined. Whew.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload