Upcoming Posts

Upcoming Posts....

Make your own partition magic software.
How to make an assembler.
What is booting?
Write a simple OS!

‎"I have no special talents. I am only passionately curious." - Albert Einstein

Thursday, January 12, 2012

Why does C++ not allow overloading ‘.’ , ‘:*’ , ‘::’ and ‘?:’ operators?

Stroustrup’s wanted to allow programmers to use all the operators with user defined data types as well. Thus he added operator overloading as feature in C++ so that programmers can define functionality of operators for user defined data types. A restriction is that the operators like ‘.’ , ‘:*’ , ‘::’ and ‘?:’ are not allowed for overloading. These operators are not meant to use with any data types. These are introduced to use language’s features like:

“.” Direct member access operator is used to access member variable/function.

“:*” De-reference pointer to class member operator is used to De-reference pointer to class member.

“::” Scope resolution operator is used to access global variable and define method outside class.

“?:” Conditional operator is like if-else condition. Why do we need to overload it.

“Sizeof” operator is used get size of an object. It can’t be overloaded because built-in operations such as incrementing a pointer into an array implicitly depend on it. Consider:

                X a[10];
                X* p = &a[3];
                X* q = &a[3];
                p++;   // p points to a[4]
                          // thus the integer value of p must be
                          // sizeof(X) larger than the value of q

Thus, sizeof(X) could not be given a new and different meaning by the programmer without violating basic language rules.

As above operators are close to the core of the language, allowing overloading of these operators can cause many problems/confusions without any benefits (“->” operator is allowed to overload to make a smart pointer class).

Reference: The Design and Evolution of C++ by Bjarn Stroustrup 

1 comment:

  1. perfect explanation about java programming .its very useful.thanks for your valuable information.java training in chennai | chennai's no.1 java training in chennai

    ReplyDelete