Q
Q
Qubc2021-08-03 20:31:43
C++ / C#
Qubc, 2021-08-03 20:31:43

Why is it possible to call a non-constant method through a constant reference (spoiler - you can’t, inattention)?

class S { 
  char array[17] ;
public:
  void f(void) { ; }
  void fc(void) const { ; }
} ;
int main (void) {
  S s;
  const S& rc = s;
  s.f();// ???????????????????????????????????????????
  s.fc();
  return 0;
}

By "const reference" is meant a reference to a constant or, as here, to a read-only object.
If you make a function with such a parameter, then everything correctly produces an error.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
J
jcmvbkbc, 2021-08-03
@Qubc

Why is it possible to call a non-const method through a const reference?
S s;
  const S& rc = s;
  s.f();// ???????????????????????????????????????????

You call a method not through a link. Through the link it will be like this:
rc.f();
and, of course, it will not compile.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question