EzDevInfo.com

operator-overloading interview questions

Top operator-overloading frequently asked interview questions

Operator overloading in Java

Please can you tell me if it is possible to overload operators in Java? If it is used anywhere in Java could you please tell me about it.


Source: (StackOverflow)

Create List of Single Item Repeated n Times in Python

I know a list comprehension will do this, but I was wondering if there is an even shorter (and more Pythonic?) approach.

I want to create a series of lists, all of varying length. Each list will contain the same element e, repeated n times (where n = length of the list). How do I create the lists, without doing

[e for number in xrange(n)]

for each list?


Source: (StackOverflow)

Advertisements

Operator overloading

What are the basic rules and idioms for operator overloading in C++?

Note: The answers were given in a specific order, but since many users sort answers according to votes, rather than the time they were given, here's an index of the answers in the order in which they make most sense:

(Note: This is meant to be an entry to Stack Overflow's C++ FAQ. If you want to critique the idea of providing an FAQ in this form, then the posting on meta that started all this would be the place to do that. Answers to that question are monitored in the C++ chatroom, where the FAQ idea started out in the first place, so your answer is very likely to get read by those who came up with the idea.)


Source: (StackOverflow)

How do I overload the [] operator in C# [duplicate]

This question already has an answer here:

I would like to add an operator to a class. I currently have a GetValue() method that I would like to replace with an [] operator.

class A
{
    private List<int> values = new List<int>();

    public int GetValue(int index)
    {
        return values[index];
    } 
}

Source: (StackOverflow)

How do I overload the square-bracket operator in C#?

DataGridView, for example, lets you do this:

DataGridView dgv = ...;
DataGridViewCell cell = dgv[1,5];

but for the life of me I can't find the documentation on the index/square-bracket operator. What do they call it? Where is it implemented? Can it throw? How can I do the same thing in my own classes?

ETA: Thanks for all the quick answers. Briefly: the relevant documentation is under the "Item" property; the way to overload is by declaring a property like public object this[int x, int y]{ get{...}; set{...} }; the indexer for DataGridView does not throw, at least according to the documentation. It doesn't mention what happens if you supply invalid coordinates.

ETA Again: OK, even though the documentation makes no mention of it (naughty Microsoft!), it turns out that the indexer for DataGridView will in fact throw an ArgumentOutOfRangeException if you supply it with invalid coordinates. Fair warning.


Source: (StackOverflow)

How can I reliably get an object's address when operator& is overloaded?

Consider the following program:

struct ghost
{
    // ghosts like to pretend that they don't exist
    ghost* operator&() const volatile { return 0; }
};

int main()
{
    ghost clyde;
    ghost* clydes_address = &clyde; // darn; that's not clyde's address :'( 
}

How do I get clyde's address?

I'm looking for a solution that will work equally well for all types of objects. A C++03 solution would be nice, but I'm interested in C++11 solutions too. If possible, let's avoid any implementation-specific behavior.

I am aware of C++11's std::addressof function template, but am not interested in using it here: I'd like to understand how a Standard Library implementor might implement this function template.


Source: (StackOverflow)

Operator Overloading with C# Extension Methods

I'm attempting to use extension methods to add an operater overload to the C# StringBuilder class. Specifically, given StringBuilder sb, I'd like sb += "text" to become equivalent to sb.Append("text").

Here's the syntax for creating an extension method for StringBuilder:

public static class sbExtensions
{
    public static StringBuilder blah(this StringBuilder sb)
    {
        return sb;
    }
} 

It successfully adds the blah extension method to the StringBuilder.

Unfortunately, operator overloading does not seem to work:

public static class sbExtensions
{
    public static StringBuilder operator +(this StringBuilder sb, string s)
    {
        return sb.Append(s);
    }
} 

Among other issues, the keyword this is not allowed in this context.

Are adding operator overloads via extension methods possible? If so, what's the proper way to go about it?


Source: (StackOverflow)

How to properly overload the << operator for an ostream?

I am writing a small matrix library in C++ for matrix operations. However my compiler complains, where before it did not. This code was left on a shelf for 6 months and in between I upgraded my computer from debian etch to lenny (g++ (Debian 4.3.2-1.1) 4.3.2 ) however I have the same problem on a Ubuntu system with the same g++.

Here is the relevant part of my matrix class:

namespace Math
{
    class Matrix
    {
    public:

        [...]

        friend std::ostream& operator<< (std::ostream& stream, const Matrix& matrix);
    }
}

And the "implementation":

using namespace Math;

std::ostream& Matrix::operator <<(std::ostream& stream, const Matrix& matrix) {

    [...]

}

This is the error given by the compiler:

matrix.cpp:459: error: 'std::ostream& Math::Matrix::operator<<(std::ostream&, const Math::Matrix&)' must take exactly one argument

I'm a bit confused by this error, but then again my C++ has gotten a bit rusty after doing lots of Java those 6 months. :-)


Source: (StackOverflow)

Should operator<< be implemented as a friend or as a member function?

That's basically the question, is there a "right" way to implement operator<< ? Reading this I can see that something like:

friend bool operator<<(obj const& lhs, obj const& rhs);

is preferred to something like

ostream& operator<<(obj const& rhs);

But I can't quite see why should I use one or the other.

My personal case is:

friend ostream & operator<<(ostream &os, const Paragraph& p) {
    return os << p.to_str();
}

But I could probably do:

ostream & operator<<(ostream &os) {
    return os << paragraph;
}

What rationale should I base this decision on?

Note:

 Paragraph::to_str = (return paragraph) 

where paragraph's a string.


Source: (StackOverflow)

__lt__ instead of __cmp__

Python 2.x has two ways to overload comparison operators, __cmp__ or the "rich comparison operators" such as __lt__. The rich comparison overloads are said to be preferred, but why is this so?

Rich comparison operators are simpler to implement each, but you must implement several of them with nearly identical logic. However, if you can use the builtin cmp and tuple ordering, then __cmp__ gets quite simple and fulfills all the comparisons:

class A(object):
  def __init__(self, name, age, other):
    self.name = name
    self.age = age
    self.other = other
  def __cmp__(self, other):
    assert isinstance(other, A) # assumption for this example
    return cmp((self.name, self.age, self.other),
               (other.name, other.age, other.other))

This simplicity seems to meet my needs much better than overloading all 6(!) of the rich comparisons. (However, you can get it down to "just" 4 if you rely on the "swapped argument"/reflected behavior, but that results in a net increase of complication, in my humble opinion.)

Are there any unforeseen pitfalls I need to be made aware of if I only overload __cmp__?

I understand the <, <=, ==, etc. operators can be overloaded for other purposes, and can return any object they like. I am not asking about the merits of that approach, but only about differences when using these operators for comparisons in the same sense that they mean for numbers.

Update: As Christopher pointed out, cmp is disappearing in 3.x. Are there any alternatives that make implementing comparisons as easy as the above __cmp__?


Source: (StackOverflow)

virtual assignment operator C++

Assignment Operator in C++ can be made virtual. Why is it required? Can we make other operators virtual too?


Source: (StackOverflow)

Override 'in' operator in Python

If I am creating my own class in Python, what function should I define so as to allow the use of the 'in' operator, e.g.

class MyClass(object):
    ...

m = MyClass()

if 54 in m:
    ...

Source: (StackOverflow)

Is there actually a reason why overloaded && and || don't short circuit?

The short circuiting behaviour of the operators && and || is an amazing tool for programmers.

But why do they lose this behaviour when overloaded? I understand that operators are merely syntactic sugar for functions but the operators for bool have this behaviour, why should it be restricted to this single type? Is there any technical reasoning behind this?


Source: (StackOverflow)

What makes Scala's operator overloading "good", but C++'s "bad"?

Operator overloading in C++ is considered by many to be A Bad Thing(tm), and a mistake not to be repeated in newer languages. Certainly, it was one feature specifically dropped when designing Java.

Now that I've started reading up on Scala, I find that it has what looks very much like operator overloading (although technically it doesn't have operator overloading because it doesn't have operators, only functions). However, it wouldn't seem to be qualitatively different to the operator overloading in C++, where as I recall operators are defined as special functions.

So my question is what makes the idea of defining "+" in Scala a better idea than it was in C++?


Source: (StackOverflow)

A positive lambda: '+[]{}' - What sorcery is this? [duplicate]

In Stack Overflow question Redefining lambdas not allowed in C++11, why?, a small program was given that does not compile:

int main() {
    auto test = []{};
    test = []{};
}

The question was answered and all seemed fine. Then came Johannes Schaub and made an interesting observation:

If you put a + before the first lambda, it magically starts to work.

So I'm curious: Why does the following work?

int main() {
    auto test = +[]{}; // Note the unary operator + before the lambda
    test = []{};
}

It compiles fine with both GCC 4.7+ and Clang 3.2+. Is the code standard conforming?


Source: (StackOverflow)