No implementation in C ++, but you can still call it

I have Simpletron.cpp , which is an empty file, a Simpletron.h , which declares a Simpletron class:

 class Simpletron { public: Simpletron(); }; 

I called Simpletron() in my main.cpp:

 #include <iostream> #include "Simpletron.h" int main(int argc, char *argv[]) { Simpletron s(); std::cin.get(); } 

The main function runs smoothly without any warnings or errors. Why is this? How can this be compiled at all if there is no add-on that the header file can use?

+7
c ++
source share
3 answers

This line:

 Simpletron s(); 

is a function prototype that declares a function named s that returns Simpletron and takes no arguments. It does not create an instance of Simpletron named s .

Now you may ask why the replicator does not complain about the non-existent s() function? Well, since you only declare s() , but don’t actually name it, it doesn’t actually refer anywhere during binding, so you are not getting any communication errors.

+24
source share
 Simpletron s(); 

This is a function declaration, not an instance of an object. An empty bracket indicates to the compiler that this function takes no arguments and returns an object of type Simpletron by value, so no constructors are called. The correct syntax has no parameters:

 Simpletron s; // You will get an error on this line, as initially expected 

C ++ 11 adds a syntax function that avoids this ambiguity:

 Simpletron s{}; // same as default-initialization 
+13
source share
  Simpletron s(); 

This is a classic case of "annoying parsing"; for the compiler, you do not create an s variable of type Simpletron , but you declare a function named s without taking any parameters and returning a Simpletron object.

This is due to the fact that this expression can be interpreted as a declaration of a function, or as a declaration of a variable; since there is a simple alternative to declaring a variable (namely, just omit the brackets), standard mandates interpret this as a function declaration.

This completes the compilation step without problems (the compiler should not have a definition of all methods, just a declaration), and probably the linker does not give any error, since the Simpletron instance is actually, so you never need to look for the constructor definition (although I don’t think that it is guaranteed to not give errors, especially a careful compiler / linker pair should be able to give you an error for a missing constructor).

+5
source share

All Articles