Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
Tutorialspoint

1 Answer
Anvi Jain

In C++, we can overload functions. Some functions are normal functions; some are constant type functions. Let us see one program and its output to get the idea about the constant functions and normal functions.

Example

#include <iostream>
using namespace std;
class my_class {
   public:
      void my_func() const {
         cout << "Calling the constant function" << endl;
      }
      void my_func() {
         cout << "Calling the normal function" << endl;
      }
};
int main() {
   my_class obj;
   const my_class obj_c;
   obj.my_func();
   obj_c.my_func();
}

Output

Calling the normal function
Calling the constant function

Here we can see that the normal function is called when the object is normal. When the object is constant, then the constant functions are called.

If two overloaded method contains parameters, and one parameter is normal, another is constant, then this will generate error.

Example

#include <iostream>
using namespace std;
class my_class {
   public:
      void my_func(const int x) {
         cout << "Calling the function with constant x" << endl;
      }
      void my_func(int x){
         cout << "Calling the function with x" << endl;
      }
};
int main() {
   my_class obj;
   obj.my_func(10);
}

Output

[Error] 'void my_class::my_func(int)' cannot be overloaded
[Error] with 'void my_class::my_func(int)'

But if the arguments are reference or pointer type, then it will not generate error.

Example

#include <iostream>
using namespace std;
class my_class {
   public:
      void my_func(const int *x) {
         cout << "Calling the function with constant x" << endl;
      }
      void my_func(int *x) {
         cout << "Calling the function with x" << endl;
      }
};
int main() {
   my_class obj;
   int x = 10;
   obj.my_func(&x);
}

Output

Calling the function with x

Advertisements

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.