Const member function arguments with C++

In C++, if we want our argument passed to a member function by reference should not get modified then that argument should be made const

In the below program, the arguments to the member function add() are passed by reference, and to make sure that the arguments won’t get modified  we declared the arguments as const

#include <iostream>
using namespace std;
class sample
{
private:
    int data;
public:
    sample()
    {
        data=0;
    }
    void changedata()
    {
        data=10;
    }
    void showdata()const
    {
    cout<<endl<<"data="<<data;
    }
    void add(sample const &s, sample const&t)
    {
        data=s.data+t.data;
    }
};
int main()
{
    sample s1;
    s1.changedata();
      sample s2;
    s2.changedata();
    sample s3;
    s3.add(s1,s2);
    s3.showdata();
    return 0;
}

Output

data=20

In case, if you try to modify the const arguments then you will get an error such as  error: assignment of member sample::data in read-only object

 void add(sample const &s, sample const &t)
    {
        s.data=100;
        t.data=200;
        data=s.data+t.data;
    }

Mohammed Anees

Hey there, welcome to aneescraftsmanship I am Mohammed Anees an independent developer/blogger. I like to share and discuss the craft with others plus the things which I have learned because I believe that through discussion and sharing a new world opens up

Leave a Reply

Your email address will not be published.