C++ syntax, "MyClass m;" versus "MyClass m();"

J

janzon

Hi!

When defining a new object m of class MyClass, with no parameters to
the constructor, one is supposed to write "MyClass m;". If one wants to
pass a parameter p to the constructor, one is supposed to write
"MyClass m(p);". It doesn't work if one writes "MyClass m();" when one
wants to pass zero parameters. Why is that? It seems inelegant and
non-symmetric to me. What reason is there behind this?

/ Me, seeking insights into C++
 
H

hit_pc

"MyClass m(p);". It doesn't work if one writes "MyClass m();" when one
wants to pass zero parameters. Why is that? It seems inelegant and
if you write "MyClass m()",
it is not a Class,it is a function declare,
it means:this is a function ,its name is m,its param is void,and it
returns sth with type MyClass.
think about this:
you can declare a function like this:int func(int a)
also you can :int func(int)
 
R

Rolf Magnus

Hi!

When defining a new object m of class MyClass, with no parameters to
the constructor, one is supposed to write "MyClass m;". If one wants to
pass a parameter p to the constructor, one is supposed to write
"MyClass m(p);". It doesn't work if one writes "MyClass m();" when one
wants to pass zero parameters. Why is that? It seems inelegant and
non-symmetric to me. What reason is there behind this?

You're right in that it is kind of unintuitive. The reason is that
"MyClass m();" already has another meaning. It declares a function taking no
arguments and returnint MyClass, similar to "int myfunc();".
 
A

Alex Vinokur

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top