C++

Examples of const objects and const member functions in C++


Examples of const objects and const member functions in C++

const objects can only call const member functions:

#include<iostream>
using namespace std;
class A
{
public:
  void fun()const
  {
    cout<<"const  A member function !"<<endl;
    }
  void fun()
  {
    cout<<" non const A member function  !"<<endl;
  }
};
int main()
{
  const A a;
  a.fun();
}

Output: const member function!

However, if you comment out the first fun, you will make an error: error C2662: “A::fun” : you cannot convert the “this” pointer from “const A” to “A” & ”.

However, const member functions can be called by non-const objects:

#include<iostream>
using namespace std;
class A
{
public:
  void fun()const
  {
    cout<<"const  A member function !"<<endl;
    }

/* void fun()
  {
    cout<<" non const A member function  !"<<endl;
  }
  */
};
int main()
{
   A a;
  a.fun();
}

Output: const member function!

Of course, non-const objects can call non-const member functions.

If you have any questions, please leave a message or come to the site community to exchange discussion, thank you for reading, hope to help you, thank you for your support of the site!