How to apply constant reference parameter on this code?
This code is passing object to a function and I want to apply constant reference parameter on this code.
class Test
{
int num;
public :
void setNum(int z)
{
num=z;
}//end mutator
int getNum()
{
return num;
}//end accessor
};//end class
void storeNumber(Test &n)
{
int a=10;
n.setNum(a);
}
void displayNumber(Test n)
{
cout<<"number="<<n.getNum()<<endl;
}
int main()
{
Test t;
t.setNum(5);
cout<<t.getNum()<<endl;
storeNumber(t);//pass by reference;
displayNumber(t); //pass by value
cout<<t.getNum();
}
This code is passing object to a function and I want to apply constant reference parameter on this code.
Any help!!
You can do for example void displayNumber(const Test &n)
but then if you call methods of the Test
class, they must have the const
qualifier too (for example int getNum() const
). If you pass Test
as const &
to a function, then you won't be able to use void setNum(int z)
function as it violates the constant
ness of the class.
Edit:
Here is the full code:
class Test
{
int num;
public :
void setNum(int z)
{
num=z;
}//end mutator
int getNum() const
{
return num;
}//end accessor
};//end class
void storeNumber(Test &n)
{
int a=10;
n.setNum(a);
}
void displayNumber(const Test &n)
{
cout<<"number="<<n.getNum()<<endl;
}
int main()
{
Test t;
t.setNum(5);
cout<<t.getNum()<<endl;
storeNumber(t);//pass by reference;
displayNumber(t); //pass by value
cout<<t.getNum();
}