How can i maintain operator's precedence order while overloading "+" and "*" in a class? e.g. I want same result on the calculation of following objects:
d=a+b*c;
d=c*a+b;
Please help!

Also tell me why simple constructor is able to call static data in a class?

Hi sumit21amig, welcome!
Don't know what you are getting at here. * ALWAYS takes precedence over +. That is just standard math. The formulas you give will only have the same result if a,b and c have the same value or some of them are zero.
Static data are always available even to a simple constructor.

of course we have BODMAS rule of arithmetic which is quite applicable with integer, float, double and etc but the behavior of arithmetic operators into the context of class/object is defined by programmer to the compiler.
So, how this precedence/BODMAS is applied in a class?
I hope i am clear.

Most of the time you don't have to bother about operator overloading in C#. The compiler is even smart enough to figure out that a string + an integer ends in a string with the number appended. The C# compiler, like any other compiler I ever used always used the BODMAS rule as you call it. If you want to change the order of calculation use brackets.
But if the expressions d=a+b*c; and d=c*a+b; always have to resolve to the same value you have to design your own math I guess.

According to some quick google searches (google makes me look so smart!) in "ECMA-334: 14.2.2 Operator overloading" there is a line that reads "User-defined operator declarations cannot modify the syntax, precedence, or associativity of an operator." So, if I understand that correctly (I'm not done with my Red Bull, so anyone out there with knowledge please reply) you can't change the precedence of operators. For a fun test, derive a class from Integer and overload * and + by swapping them (make * actually add, and + multiply), then try to solve

MyInteger two = 2, three = 3, four = 4; MyInteger X = two * three + four;
commented: He that's a nice point of view! :) +5

How can i maintain operator's precedence order while overloading "+" and "*" in a class? e.g. I want same result on the calculation of following objects:
d=a+b*c;
d=c*a+b;
Please help!

Also tell me why simple constructor is able to call static data in a class?

As ddanbe pointed out, multiplication takes precedance so your equations are calculated as:

d = a + (b*c);
d = (c*a) + b;

You would need to enclose parts in brackets if you want them to be calculated prior to the multiplication:
d = (a + b) * c;
d = c * (a + b);

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.