Learning
Learning

Reputation: 219

Why the following c++ code don't compile?

#include <iostream>
int test( const double *t1,const double **t2 )
{
  return 0;
}
int main(int argc, char*argv[])
{
  double *t1 = new double;
  const double ** t2 = new double *;
  test(t1, t2);
}

The error is :

cannot convert double ** to const double **

It compiles if I remove the 2 occurence of const though..

Upvotes: 0

Views: 200

Answers (4)

Robert Parcus
Robert Parcus

Reputation: 1049

it should at least compile now

int main(int argc, char*argv[])
{
  double *t1 = new double;
  const double ** t2 = new const double *;
  test(t1, t2);
}

Upvotes: 0

Suma
Suma

Reputation: 34403

Such conversion is not allowed, because if the conversion would be possible, you could modify the const object in a following way:

#include <stdio.h>

const double A0 = 0;
const double A1 = 1;
const double* A[2] = { &A0, &A1 };
double * B[2];

int main()
{
  double** b = B;
  const double ** a = b; // illegal
  //const double ** a = (const double **)b; // you can simulate it would be legal

  a[0] = A[0];
  b[0][0] = 2; // modified A0

  printf("%f",A[0][0]);
}

For a simulated result, check the code at IdeOne.com - you will get SIGSEGV (const object was placed in read only memory and you are trying to modify it). With a different platform the object might be modified silently.

Upvotes: 0

Puppy
Puppy

Reputation: 146910

The issue is that by de-referencing in a certain way, you can violate const correctness with double pointers.

Upvotes: 2

Diff.Thinkr
Diff.Thinkr

Reputation: 855

Make it

const double ** t2 = new const double *;

Upvotes: 3

Related Questions