I have come across a function definition starting as:
int operator*(vector &y)
{
// body
}
After putting * just after operator and before opening brace of argument, what does this function mean?
This is an operator * overload. The syntax you should use is *(y) while y is of type vector.
It allows you a reference like implementation, something similar to pointer reference in C. Of course the actual meaning depends on the body. e.g. you can return a reference to an internal element in the vector.
This is a function overload for the * operator.
Its function overloading which overload the de-reference operator *.
It is either a dereferencing operator or a multiplication operator override. It is dereferencing if it is in a namespace and multiplication if it is inside a class. Since it has a body and no class scope I will also assume that it is a dereferencing.
Actually its not a deferencing operator as in *ptr! Its actually an operator such as a multiplication operator. Here is a simple example
#include <iostream>
using namespace std;
struct Int{
int val;
Int(const int val = 0) : val(val){}
int operator*(const Int& number)const{
return val * number.val;
}
};
int main(){
Int n(4), m(5);
cout << n * m << endl; //use the operator*() implicitly
cout << (n.operator*(m)) << endl; //use the operator* explicitly
}
To define a de-ferenceing operator, its prototype would be operator*(). Look here for more information. Here is a live code to test.
Related
int operator++(int){
//relevant code
}
I dont seem to understand the workings of the code for overloading post increment operator given
above
I know that the int as a dummy parameter is given to differentiate between pre-increment and post increment operator overloading.
If a is a object of the class in which these operators are overloaded ,both ++a and a++ should have a equivalent representation as a.operator++()(as per my understanding ),how does the int parameter help in resolving it as a post increment operator?
-A c++ beginner
If a is a object of the class in which these operators are overloaded
,both ++a and a++ should have a equivalent representation as
a.operator++()(as per my understanding ),how does the int parameter
help in resolving it as a post increment operator?
The post increment operator can be called with a dummy int argument but normally this isn't what you would do. In the following, typically you would define void foo::operator++(int) so that you can make a call like (1) but (2) is legal.
#include<iostream>
struct foo {
void operator++() {
std::cout << "pre\n";
}
void operator++(int) {
std::cout << "post\n";
}
};
int main() {
foo a;
// these yield: pre
++a;
a.operator++();
// these yield post:
a++; // (1)
a.operator++(int{}); // (2)
}
When the compiler sees ++a, and a is not a built-in type, then the compiler looks for either a::operator++() or operator++(a&) and if found then calls it.
When the compiler sees a++, and a is not a built-in type, then the compiler looks for either a::operator++(int) or operator++(a&, int) and if found then calls it.
See Increment/decrement operators on cppreference.com for more details.
Is it possible to create an "address of" (&) operator overload that would allow passing an arg? So kind of a mixture between overloading the operator [] and operator &.
So regular [] overload can be used like this
val = myobj[arg];
where:
SomeReturnType MyClass::operator[](SomeArgType i)
{
// Code to handle indexing
}
But if we want a pointer to that item, what I'm looking for would provide this use:
ptr = &myobj[arg];
Maybe this isn't possible directly, and I know there's other ways to achieve this, but if it is possible I do not know the syntax.
You do not need to overload adress of operator when operator[] returns a reference:
#include <iostream>
struct foo {
int x;
int& operator[](int){
return x;
}
};
int main() {
foo f;
std::cout << &f.x << "\n";
std::cout << &f[42] << "\n";
}
Possible output:
0x7ffc8cd2d46c
0x7ffc8cd2d46c
The example uses only a single int, but it will be the same when operator[] is returning reference to an element of some container.
Returning a copy from operator[] and then get the adress of the original element is not possible via operator& overload (unless you return some proxy that holds both, the copy of the element and the adress of the original, from operator[]).
#include<iostream>
using namespace std;
class binary
{
protected:
int num;
public:
binary(int a)
{
num=a;
}
binary operator - (binary b1)
{
binary b(0);
b.num=~(b1.num-1);
return b(b.num);
}
void display()
{
cout<<"Negative is: "<<num;
}
};
int main()
{
int a;
cout<<"Enter no.: ";
cin>>a;
binary b(a);
binary b1=-b;
b1.display();
}
In the above program, it shows that the return type of overloading operator should be should be of form int&. Can anyone please explain to me what that means?
Is the return type wrong ? yes returning b(b.num); is wrong, it should return only object b.
You are overloading unary minus using member function, it should have zero argument because member function having this pointer, you can use this pointer to get data member of class.
binary operator - ()
{
binary b(0);
b.num = ~(this-> num-1);
return b;
}
You improperly declared the unary operator-. There are two variants of operator-: unary and binary. Since this is implicitly on the left hand of operator-, unary operator requires no arguments and binary requires one argument on the right hand. Therefore you declared binary operator-. Please try like below
binary operator - ()
{
return binary(~(num-1));
}
binary operator-(binary b1) { ... }
defines the binary - operator between two objects of type binary.
To be able to use
binary b1=-b;
you need to overload the unary - operator. That can be done using:
binary operator-() { ... }
I suspect you want to implement the unary - operator. Your implementation can use this instead of b1. I suggest making he member function const since it does not modify the this object.
binary operator-() const
{
binary b(~(this->num-1));
return b;
}
That will also allow you to use:
binary b1 = -binary(10);
Because you have to parse integer value
But as given in code return b(b.num)
instead of that it should be "return b".
I understand my second statement that "why & is not needed for normal function pointers" because function name itself is address of the function.
What I do not understand is why '&' is strictly needed for member function pointers?
Examples:
Normal function pointers:
int add(int a, int b) {
return (a + b);
}
int (*fp)(int, int);
fp = add;
(*fp)(2, 3) // This would give me addition of a and b, i.e. 5
Member function pointers:
class ABC {
public:
int i;
ABC() { i = 0; }
int addOne(int j) {
return j + 1;
}
};
// Member function pointer
int (ABC::*mfp)(int);
// This is what I am talking about. '&' in below line.
mfp = &ABC::addOne;
ABC abc;
std::cout << (abc.*mfp)(2) << std::endl;
It seems to me that the address-of operator is necessary for member function pointers because the right-hand side (rhs) of the declaration is a constant rather than a variable.
We wouldn't say
int (ABC::*mfp)(int);
mfp = ABC::addOne();
because that would be to invoke a function.
Furthermore, the scope resolution operator :: has the highest precedence in the C++ table of operator precedence:
https://github.com/MicrosoftDocs/cpp-docs/blob/master/docs/cpp/cpp-built-in-operators-precedence-and-associativity.md
The :: operator is evaluated before any other operators are on the rhs. I suppose the complier wonders "Hmmmm...what's that? That should be a function, but..." and then sees the address-of operator and knows what the developer needs.
I've already overloaded operator [ ] to enable element access.
definition
double Matrix::operator[ ](const & int i){
return data[i]; // data[] is a member array: thrust:: device_vector
}
usage
Matrix m = ... // initialize
std::cout << m[3] << std::endl;
But now I want to access element by index so that assign new value to it.
usage
m[3] = 0.;
I understand the return value of the operator overload function must be an lvalue. I guess I should return a reference, but not sure how this is done. Thanks!
EDIT
Now I changed my definition to double &, but it still complains:
error: initial value of reference to non-const must be an lvalue
The array refers to a thrust::device_vector, which can be assigned value by index:
Thrust::device_vector<double> M(10);
M[3] = 0.;
Just replace
double ....
with
double& .....
change your definition to
double& Matrix::operator[ ](const & int i){
return data[i]; // data[] is a member array
}
Note, you should not use reference for an integer argument. It is usually used for complex classes for avoiding the copy. I would also suggest as a side note, to use m_memberVariable unless you use pimpl. This is what you should write:
double& Matrix::operator[ ] (const int i) {
return m_data[i]; // data[] is a member array
}
Note, you will need to add the '&' marker also in the class header where the method is declared.
This is all provided you have something like this in the class header:
class Matrix
{
private:
double m_data[100];
public:
double& operator[] (const int i);
};
Here you can read further details on the subscript operator overloading. This is another url for learning more about references.
As for a bit of inline explanation why it works like that:
You are trying to use the subscript operator on the left hand for assignment, hence the return value of such an operator overload has to be an l-value as you correctly state it. This is because if you return a value instead of reference, the left hand side in the usage would simply return that value which would evaluate to x = 0 where replace x with a value like 1. That is why you will get a compiler error in such cases.
Usually you chose to have a pair of operators. One for access:
double Matrix::operator[ ] const (const & int i){
return data[i];
}
and the other for assigment:
double &Matrix::operator[ ](const & int i){
return data[i];
}
If you call [ ] operator on a const object the first operator is really called. In other cases, both in access as well as assgnement, the second one is called.
You get error:
error: initial value of reference to non-const must be an lvalue
because data is (probably) a local variable. Make it a Matrix class private data member if it's not already.