-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.

iso42
  • 21
  • 1
  • 7
  • With what you have right now, there's no reason for a non-const version, or even a non-static version – Ranoiaetep Feb 14 '23 at 05:36
  • @Ranoiaetep the idea behind this is to explore how casting operators are useful and im trying to explore that. – iso42 Feb 14 '23 at 06:08

1 Answers1

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.