0

I'm pretty new to c++, i'm now trying to learn all the basics, I know when default constructors are called, but when i tried different syntax it doesn't work like i expected.

Look at the following code:

class a;
class b();
class c(NULL);

'class' is a class i created with default constructor, for a and c everything works well, but for b it just won't recognize the variable as a class member.

As i see it b and c are basically the same, what's wrong than? Thanks!

2 Answers2

4

Don't name your class "class", as it is a reserved name.

As for C++, if the constructor takes no parameters, you instantiate it using

Foo a;   // note, if you are using c++11, you can do Foo a{};

As opposed to:

Foo b();

Which actually does something totally unexpected*, and declares a function named b that returns a Foo instance.

As for Foo c(null), it won't compile as there is no default constructor that takes an argument.


* It is referred to as "the most vexing parse", though I find that to be an exaggeration. It can certainly catch you by surprise, but just knowing that you can declare a function prototype inside a function, should be enough to remove the "vexing" aspect.

In other words int getMyInt(); is obviously a function prototype when placed outside any function definitions. However, since this is also the case when inside a function definition, int getMyInt(); doesn't do anything it wouldn't normally do... which is to define a function prototype getMyInt that returns an integer.

swalog
  • 4,403
  • 3
  • 32
  • 60
2

b is interpreted as a declaration of a function taking no arguments and returning an object of type class.

This is known as the most vexing parse. Edit: This is not the most vexing parse.

Community
  • 1
  • 1
Emil Laine
  • 41,598
  • 9
  • 101
  • 157