S
subramanian100in
The following is a beginner's question.
Suppose TYPE1 and TYPE2 are two types for which suitable ctors and
operator= are defined.
Suppose I have
class Test
{
TYPE1 mem1;
TYPE2 mem2;
public:
Test & member1(const TYPE1 & val1);
Test & member2(const TYPE2 & val2);
Test & display( ) { /* display mem values */ return *this; }
const Test & display( ) const { /* display mem values */ return
*this; }
};
Test & Test::member1(const TYPE1 & val1)
{
mem1 = val1;
return *this;
}
Test & Test::member2(const TYPE2 & val2)
{
mem2 = val2;
return *this;
}
Suppose I define,
TYPE1 val1;
TYPE2 val2;
Test obj;
obj.display( ).member1(val1).member2(val2).display( );
const Test const_obj;
const_obj.display( );
Suppose the body of both the display( ) functions are the same. That
is, display( ) does not modify the data members of the object. The non-
const version of display( ) function is provided only for chaining.
The const version of display( ) function is provided to be called on
const Test objects. Given this, I have the following questions:
1)Is it advisable to overload a function like display( ) only on const
(everything else being the same for this function) for chaining
purpose when it does not modify the data members of the object
2) When is overloading a function, only on const inevitable ?
Kindly explain
Thanks
V.Subramanian
Suppose TYPE1 and TYPE2 are two types for which suitable ctors and
operator= are defined.
Suppose I have
class Test
{
TYPE1 mem1;
TYPE2 mem2;
public:
Test & member1(const TYPE1 & val1);
Test & member2(const TYPE2 & val2);
Test & display( ) { /* display mem values */ return *this; }
const Test & display( ) const { /* display mem values */ return
*this; }
};
Test & Test::member1(const TYPE1 & val1)
{
mem1 = val1;
return *this;
}
Test & Test::member2(const TYPE2 & val2)
{
mem2 = val2;
return *this;
}
Suppose I define,
TYPE1 val1;
TYPE2 val2;
Test obj;
obj.display( ).member1(val1).member2(val2).display( );
const Test const_obj;
const_obj.display( );
Suppose the body of both the display( ) functions are the same. That
is, display( ) does not modify the data members of the object. The non-
const version of display( ) function is provided only for chaining.
The const version of display( ) function is provided to be called on
const Test objects. Given this, I have the following questions:
1)Is it advisable to overload a function like display( ) only on const
(everything else being the same for this function) for chaining
purpose when it does not modify the data members of the object
2) When is overloading a function, only on const inevitable ?
Kindly explain
Thanks
V.Subramanian