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 just runs smoothly without any warning or error. Why is that? How does that even compile if there is no inplementation the header file could link to?
This line:
Simpletron s();
is a function prototype, declaring a function named s
, returning a Simpletron
and taking no arguments. It does not create a Simpletron
instance named s
.
Now you might ask, why doesn't the linker complain about the non-existent s()
function instead? Well, since you're only declaring s()
but never actually calling it, it's not actually referenced anywhere during linking, so you get no link error.
Simpletron s();
This is function declaration, not an object instantiation. The empty parenthesis tells the compiler this function takes no arguments and returns an object of type Simpletron
by value, so no constructors are called. The correct syntax is without the parameters:
Simpletron s; // You will get an error on this line, as initially expected
C++11 adds a syntactical feature that avoids this ambiguity:
Simpletron s{}; // same as default-initialization
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With