Reputation: 6801
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?
Upvotes: 8
Views: 2542
Reputation: 51870
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.
Upvotes: 25
Reputation: 126837
Simpletron s();
This is a classic case of "vexing parse"; for the compiler, you are not creating a variable s
of type Simpletron
, but you are declaring a function named s
, taking no parameters and returning a Simpletron
object.
This comes from the fact that this expression could be interpreted both as a function declaration and as a variable declaration; since to declare the variable there's an easy alternative (namely, just omit the parentheses) the standard mandates to interpret this as a function declaration.
This passes without problems the compiling phase (the compiler doesn't need to have the definitions of all the methods, just the declarations), and probably the linker doesn't give any error since no instance of Simpletron
is actually created, so it never needs to actually look for the constructor definition (although I don't think that it's guaranteed not to give errors, a particularly thorough compiler/linker couple should be able to give you an error for the missing constructor anyway).
Upvotes: 5
Reputation: 96810
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
Upvotes: 13