-1

Why does const create a different signature when its applied to a struct pointer as opposed to a struct?

E.g.

typedef struct test_s {
  int foo;
} test;

void foo(test *ptr){
   return;
}

// This is ok
void foo(const test *ptr){
   return;
}

void foo(test t){
   return;
}

//This is an error
void foo(const test t){
   return;
}

(tested on gcc version 4.9.2)

To be more specific, why is it that the bottom one is an error when the pair with the pointers is not an error. The referenced duplicate question (Functions with const arguments and Overloading) would also seem to argue that the case with the pointers should be duplicates.

Community
  • 1
  • 1
chacham15
  • 13,719
  • 26
  • 104
  • 207
  • Think in terms on what arguments the function can take. The last 2 can take exactly the same arguments, the last one just arbitrarily decides to makes its internal copy constant (implementation detail). The very first one cannot take a pointer to a constant, so they really are different functions, seen from the outside. – Marc Glisse Jul 06 '16 at 05:47

1 Answers1

1
void foo(const test t){
   return;
}

is an error since it is the same as:

void foo(test t){
   return;
}

which makes it a duplicate of the previous function.


When the argument to a function is test*, you can dereference the pointer and modify it. The modification will be visible in the calling function.

void foo(test *ptr){
   ptr->foo = 10;    // The state of the object in the calling function
                     // is changed.
   return;
}

When the argument to a function is const test*, you can dereference the pointer to access it but not modify it.

void foo(const test *ptr){
   std::cout << ptr->foo << std::endl;  // OK
   ptr->foo = 10;                       // Not OK
   return;
}

For the same reason, you can overload:

void foo(test& t);
void foo(const test& t);

When you try to overload

void foo(test t);
void foo(const test t);

Both are equally good candidates when you call it. The compiler cannot disambiguate between the two. In addition, take a look at one of the answers to the dupe. It cites the section of the C++ standard that states why the last two are equivalent.

Community
  • 1
  • 1
R Sahu
  • 204,454
  • 14
  • 159
  • 270
  • 2
    thats the question: why is that a duplicate and the example with the pointers not a duplicate? – chacham15 Jul 06 '16 at 05:48
  • @chacham15 Compiler can easily differentiate between a pointer-to-non-const and a pointer-to-const. Or you thought `const test*` is a `const` pointer? – LogicStuff Jul 06 '16 at 05:52
  • @LogicStuff the question is why can it differentiate between `const test*` and `test *` but not between `const test` and `test`? – chacham15 Jul 06 '16 at 05:53
  • @chacham15, see the updated answer. – R Sahu Jul 06 '16 at 06:14