raja
raja

Reputation: 179

Few doubts regarding 1.constructor and 2.array definition at compile time

Please help me clear the concepts with following problems: (executed and tested on linux,gcc)

Problem 1:

In the following simple example what exactly meant by A a()??

I found that this is not a definition of default constructor but a() is a function with return type is A.

If it is correct then why this code does not give me any linker error or runtime error.This code runs and links smoothly as if it knows the definition of function a().

class A
{
  public:
     void print()
     {
       printf("In class A\n");
     }
};


int
  main()
  {
    A a();
    //a.fun();  //throws error "request for member ‘fun’ in ‘a’, which is of type ‘A()’"
  } 

problem 2.

In the following code the definition of array b throws error. I am not able to find the exact reason for this behavior.

int a[]={3,4,21,5,7,86};
 int b[a[3]];     //this throws error why???

 int
  main() { ... }

Upvotes: 0

Views: 68

Answers (4)

Mooing Duck
Mooing Duck

Reputation: 66951

A a(); This tells the compiler that a function a exists. Compiler says OK! But since it's never USED, the linker never check its, and so there's no linker error.

int a[]={3,4,21,5,7,86}; Unfortunately, the elements of array are not considered compile time constants and thus cannot be used to initialize arrays nor template parameters. You'll have to set the size of B another way, or do it dynamically at runtime: int *b = new int[a[3]];

Upvotes: 1

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272657

Problem 1

This is known as the most vexing parse. The following:

A a();

is a function declaration. You are not calling that function, so the linker is not obliged to resolve it. That explains why you don't see any error.

Problem 2

The size of an array must be specified with a constant expression. a[3] is not a constant expression.

Upvotes: 2

Sarfaraz Nawaz
Sarfaraz Nawaz

Reputation: 361612

A a();

Its a function declaration with name a which takes no argument and returns A. Its not a variable declaration.


int a[]={3,4,21,5,7,86};
int b[a[3]];     //this throws error why???

In C++, size of an array should be a const-expression, but a[3] is NOT a const expression. Hence the error.

However if you do this:

const int a=21;
int b[a];   //okay - now a is const expression.

Then its okay.

Upvotes: 0

BЈовић
BЈовић

Reputation: 64253

Regarding problem 2 : c++ doesn't support variable array size

Upvotes: 0

Related Questions