Creating a const class type object provides the same effect as it does on fundamental types. We can’t modify the public data members of const class type objects and call non-const member functions. For example,
#include <iostream>
struct Point
{
int x{};
int y{};
void print()
{
std::cout << x << ", " << y << "\n";
}
};
int main(int argc, char const *argv[])
{
const Point p{1, 2};
p.print(); // not allowed calling a non-const member function
p.x = 1; // not allowed to modify data member
return 0;
}Const member function
A const member function can’t modify the implicit passed object’s data members and can’t call non-const member functions. For a const class type object, we can only call const member functions. For example,
#include <iostream>
struct Point
{
int x{};
int y{};
void print() const
{
std::cout << x << ", " << y << "\n";
}
};
int main(int argc, char const *argv[])
{
const Point p{1, 2};
p.print(); // this works.
return 0;
}If object is made non-const, still we can call const member function. For example,
Point p{1, 2};
p.print(); // this still works.Overloading member function with const
We can overload member function using const. If object is const and the member function is called, the const member function is called. If object is non-const, the non-const member is called. For example,
struct Point
{
int x{};
int y{};
void print() const
{
std::cout << x << ", " << y << "\n";
}
void printMsg()
{
std::cout << "Non const member function \n";
}
void printMsg() const
{
std::cout << "const member function \n";
}
};
int main(int argc, char const *argv[])
{
const Point p{1, 2};
p.printMsg();
Point p2{3, 4};
p2.printMsg();
return 0;
}
It should print
const member function
Non const member function