1

This question might be a little odd and I could not find anything about it on the web. This is mostly about the c++ syntax.

Suppose I have the following struct

struct foo
{
 void someMethod();
};

Now here we could create an instance of this struct and use its method as such

foo().someMethod();       // Works fine - Create instance on stack and called its method
foo* p = new foo(); // Works fine - p points to object on the heap

Now my question is - I have seen in some places the following

foo* p = new foo; //Not new foo(); // Its missing `()` at the end;

so whats the difference between declaring foo in the following two ways for an object that does not require a parameter in the contructor

foo(); and foo;

if there is no difference in the two then why cant we do

foo.someMethod();

this is just a question that I am curious about.

Rajeshwar
  • 11,179
  • 26
  • 86
  • 158
  • 1
    possible duplicate of [Do the parentheses after the type name make a difference with new?](http://stackoverflow.com/questions/620137/do-the-parentheses-after-the-type-name-make-a-difference-with-new) – Brian Cain Apr 03 '14 at 02:20
  • You can't do `foo.someMethod();` because `foo` is the name of a class, and the `.` operator requires an object (i.e. an instance of that class) on the left. However, the `new` expression requires the name of a class, with the option of an initializer or construction arguments. – M.M Apr 03 '14 at 04:01

1 Answers1

0

There are some subtle differences, see Do the parentheses after the type name make a difference with new?

Community
  • 1
  • 1
Arun
  • 19,750
  • 10
  • 51
  • 60
  • The meaning of `new foo()` changed between C++98 and C++03 so I am pretty wary of using it in my own code; if zero-initializing is important then I add a constructor. – M.M Apr 03 '14 at 04:04