Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Foo(b) compile successfully in C++? [duplicate]

There is a strange behavior when I compile the below code:

class Foo {
};
int main() {
    Foo(b);
}

It compiles successfully even without declaration of b. Any explanation for this?

like image 388
Sarvesh Avatar asked Mar 08 '20 04:03

Sarvesh


People also ask

Can C program be compiled in C++ compiler?

Any C compiler that is compatible with the Oracle Developer Studio C compiler is also compatible with the Oracle Developer Studio C++ compiler. The C runtime library used by your C compiler must also be compatible with the C++ compiler.

Is there something we can do in C but not in C++?

There's no computation you can accomplish in one language but not the other. There are programs that will do one thing in C and something else in C++ (or fail to compile) according to the Standard, although rewriting these is usually trivial.

Why compile is used in C plus plus language?

Because computer architecture is made up of electronic switches and cables that can only work with binary 1s and 0s, you need a compiler to translate your code from high level C++ to machine language that the CPU can understand.

Is C code compatible with C++?

C++ is a subset of C as it is developed and takes most of its procedural constructs from the C language. Thus any C program will compile and run fine with the C++ compiler. However, C language does not support object-oriented features of C++ and hence it is not compatible with C++ programs.


Video Answer


1 Answers

It's a declaration itself. It declares a variable named b with type Foo, i.e. the same effect as Foo b;.

[stmt.ambig]/1

There is an ambiguity in the grammar involving expression-statements and declarations: An expression-statement with a function-style explicit type conversion as its leftmost subexpression can be indistinguishable from a declaration where the first declarator starts with a (. In those cases the statement is a declaration.

and [stmt.ambig]/2

The remaining cases are declarations. [ Example:

class T {
  // ...
public:
  T();
  T(int);
  T(int, int);
};
T(a);               //  declaration

...

like image 191
songyuanyao Avatar answered Oct 31 '22 06:10

songyuanyao