need brackets for default constructor?

Hi,
I am confused with the following, any one know why if the bracket is needed for Stock a = stock();
but not for:
Stock a = new stock;
Stock a = Stock(); calls an constructor with no parameters (not necessarily the default). Stock a = new Stock; calls the default constructor.
Then why I can not call the following ?
Stock a = Stock;
or
Stock a = new Stock();
Anyone give me some hint on this one? Thanks.
Then why I can not call the following ?
Stock a = Stock;


Stock a; //this is enough(it cals default constructor)

Stock a = Stock is interpreted as assign class type to the a object.
class name is indentifikator not object nor constructor, it is used to make new object.
in your case you have used that type once on the left side, no need to do so one more time on the right cos (compiler is not blind he see class type on the left which is enough)


or
Stock a = new Stock();

a must be pointer !! (cos he is pointing to the memory on the heap)

Stock* a = new Stock();

you may aloso use:

Stock* a = new Stock;
Last edited on
If you have not provided a user-defined default constructor

Stock a = new Stock();

will zero all the class members, whereas

Stock a = new Stock;

will create an unitialized object.

As soon as you provide a constructor, the () no longer results in zero init. You're responsible for init-ing all your own members.

Technically, the form with the bracket is not triggering the default constructor. It's performing value initialization.

See "Is there an implicit default constructor in C++?" (esp. the final post)
http://stackoverflow.com/questions/563221/is-there-an-implicit-default-constructor-in-c

Andy
Last edited on
I never know () can trigger a default constructor which can zero your data if you dont have one.
Thanks for both of you.
I guess no matter what, it is better to add () like the following then ? as if you do not have default constructor, it will zero out data; if you have, with () and without () will be the same:
Stock a();

Stock a = Stock();

Stock *a = new Stock();

The reason why I ask is I vaguely remember when I take the class, the teacher told me NEVER use () because it is trying to define a new method or something.
Last edited on
The reason why I ask is I vaguely remember when I take the class, the teacher told me NEVER use () because it is trying to define a new method or something.

The () only works when you use new.

The first form you quote in the prev. post

Stock a();

is the one you should never use. This does look like a function decl.

VC tells me:
warning C4930: 'Stock a(void)': prototyped function not called (was a variable definition intended?)


Andy
Last edited on
Topic archived. No new replies allowed.