ipkiss
ipkiss

Reputation: 13671

Question about overloaded member functions in C++?

I am reading some C++ text from the address https://cs.senecac.on.ca/~chris.szalwinski/archives/btp200.081/content/overl.html. in the first lines, they say:

The signature of a member function consists of:

I don't understand what they mean by saying "the const status of the function".

Can anyone elaborate on that, please? Thanks.

Upvotes: 1

Views: 118

Answers (3)

Ozair Kafray
Ozair Kafray

Reputation: 13549

Declaring a member function as const tells the compiler that the member function will not modify the object's data and will not invoke other member functions that are not const.

The compiler will check to make sure that you really don't modify the data. You can call a const member function for either a const or a non-const object, but you can't call a non-const member function for a const object (because it could modify the object).

You can read more about constness in C++ here.

Upvotes: 0

Chowlett
Chowlett

Reputation: 46675

In C++, you can declare a member function of a class to be const, by appending that keyword to its signature (for instance, int MyClass:doSomething(int param) const {...}). Doing so guarantees that the function won't change the (non-mutable) members of the class object on which the function is called - and hence it can be called with const instances of that class.

It is permissible to have two different member functions for a class whose signature differs only in whether they are declared const or not.

Upvotes: 4

Johannes Schaub - litb
Johannes Schaub - litb

Reputation: 507373

They mean to sum up the items of where functions must differ in order to be put into the same class scope. The const at the end is:

struct A {
  void f();
  void f() const;
};

These are valid overloads. The first is called if you call f on a A, and the second is used if you call it on a const A:

A a;
a.f(); // takes first

A const& b = a;
b.f(); // takes second

Note that the term "signature" is misused here. The signature of a function is more broad, and includes also the class of which a function is a member of. A signature uniquely identifies a function.

Upvotes: 3

Related Questions