-1
class nums {  public: int sum(int a,int b) const {   return a+b; } int sum(int a,int b) {   return a+b; } }; int main() { const nums a; a.sum(5,10); nums  b; b.sum(1,2); } 

I am trying remove two functions for const objects and non const objects replace with one function using casting operators.

2
  • With what you have right now, there's no reason for a non-const version, or even a non-static version Commented Feb 14, 2023 at 5:36
  • @Ranoiaetep the idea behind this is to explore how casting operators are useful and im trying to explore that. Commented Feb 14, 2023 at 6:08

1 Answer 1

0

You can use int sum(int a,int b) const even if the object isn't marked as const. See this answer.

So, the following code would compile:

class nums { public: int sum(int a,int b) const { return a+b; } }; int main() { const nums a; a.sum(5,10); nums b; b.sum(1,2); } 

Link to Compiler Explorer.

Sign up to request clarification or add additional context in comments.

3 Comments

Yes, that is possible but I want to explore how casting operators will work. Can we do this casting operators?
@iso42 wdym by "casting operators" ?
you can this refer to this link

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.