Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

No implementation in C++ but can still call it

Tags:

c++

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?

like image 474
octref Avatar asked Sep 24 '13 00:09

octref


2 Answers

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.

like image 200
Nikos C. Avatar answered Sep 22 '22 00:09

Nikos C.


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
like image 44
David G Avatar answered Sep 23 '22 00:09

David G