As we know that class is a user defined datatype which means that operations that you can do with inbuilt data types (like int or float), you can do it with class objects. e.g.
As shown in above example, we are trying to add class objects c1 and c2 at line #15 like line #11 but how would compiler know how to add two class objects. what is the definition of addition of two class objects? Compiler can't figure it out itself. You would have to define it yourself in a function and these special functions where you define behavior of an operator is called operator overloading. Let us see how to define a function to overload operator say addition(+)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | class complex { int real; int imaginary; complex(int a, int b) : real(a), imaginary(b) {} }; int main() { int a = 10; int b = 20; int c = a+b; //addition of two integers complex c1(5,10); complex c2(10,20); complex c3 = c1 + c2; // addition of two clsss objects } |
As shown in above example, we are trying to add class objects c1 and c2 at line #15 like line #11 but how would compiler know how to add two class objects. what is the definition of addition of two class objects? Compiler can't figure it out itself. You would have to define it yourself in a function and these special functions where you define behavior of an operator is called operator overloading. Let us see how to define a function to overload operator say addition(+)
1 2 3 4 5 6 7 8 9 10 11 | class complex { int real; int imaginary; complex(int a, int b) : real(a), imaginary(b) {} complex operator+(complex rhs) { complex result; result.real = real + rhs.real; result.imaginary = imaginary + rhs.imaginary; return result; } }; |
No comments:
Post a Comment