Stucture in C++ - c++

I encountered this code but I could not understand the functionality of this code.
It would be a great help if someone could explain it .
struct A{
int i,j;
A(int ii,int jj) : i(ii),j(ii){}
A(const A&a){
}
A& operator =(const A& a){
i=a.i;j=a.j;
}
};
int main()
{
int i;
A a(1,2);
A b(2,3);
A z = (a=b);
cout<<z.i<<" "<<z.j<<endl;
system("pause");
return 0;
}

Explanation:
struct A{
int i,j;//members i and j
A(int ii,int jj) : i(ii),j(ii){} //A constructor. Short form of A(int ii,int jj){i = ii;j = jj;} Original code is wrong too. Should be j(jj) instead of j(ii)
A(const A&a){}//Another constructor. It is missing the assignment
A& operator =(const A& a){
i=a.i;j=a.j;
}//Equal operator overload definition for A = another A. It copies the data from another A and assign to this new one
};
Complete working code:
#include <iostream>
using namespace std;
struct A{
int i,j;
A(int ii,int jj) : i(ii),j(jj){}
A(const A&a){i=a.i;j=a.j;}
A& operator =(const A& a){i=a.i;j=a.j;}
};
int main()
{
int i;
A a(1,2);
A b(2,3);
A z = (a=b);
cout<<z.i<<" "<<z.j<<endl;
return 0;
}

Your problem is this line:
A z = (a=b);
It ends up invoking both your operator= method and your Copy Constructor. When a = b is executed, it uses the operator= method because a already exists and then a reference to a is returned. You're essentially calling a.operator=(b).
When A z = ... is executed, it actually uses the Copy Constructor A(const A&a), not the operator= method because z does not exist yet. Since z is being created by that copy constructor and i and j are never initialized, when you try to print them out, you get whatever junk was located in the memory reserved for i and j.
Another way to view this line:
A z = (a=b);
Is actually like this:
A z(a.operator=(b));
Here's a full example:
int main()
{
A a(1,2);
A b(2,3);
a = b; //calls A& operator=(const A& a)
A z = a; //calls A(const A& a)
}
In conclusion, the fix is to do this:
A(const A& a)
{
i = a.i;
j = a.j;
}

Three mistakes:
1.A(int ii,int jj) : i(ii),j(ii /* jj here? */){}
2.The copy constructor should initialize the members: A(const A&a): i(a.i), j(a.j) {}
3.You should Add return *this in operator=:
A& operator =(const A& a){
i=a.i;j=a.j;
return *this;
}

The OP has asked the operator overloadin part. if we take a as const how can we edit it.
The operator overloading part is:
A& operator =(const A& a){
i=a.i;j=a.j;
}
When you write a=b, you only expect a to change and not b. This is enforced by the const specifier in the function argument definition. This const specifier has nothing to do with whatever appears on the left hand side of the equal sign. It only says that the right hand side of the equal sign will not be modified.

Related

Clearing a class instance with a member that has a deleted assignment operator

I wanted to clear / reinstansiate a instance of a class using the assignment operator, but some members in that class have their assignment operator deleted. So when i try to assign it to a new instance it keeps its old values.
Heres a example:
#include <cstdio>
class C
{
C operator= (const C&) = delete;
};
class B
{
public:
int x = 0;
C c;
B& operator=(const B& other)
{
return B();
}
};
int main()
{
B b;
b.x = 5;
b = B();
printf("%i\n", b.x); // prints 5, should print 0
return 0;
}
Is there some simple workaround for this without writing a method that clears all of its members? Why does this happen?
Why does this happen?
Your current implementation of operator=() is fubar.
B& operator=(B const &other)
{
x = other.x;
return *this;
}
you should also test for self-assignment, before you do anything, though, since copying members can be quite expensive:
B& operator=(B const &other)
{
if(this != &other)
x = other.x;
return *this;
}

C++ return value from a class-member function

I can't understand why a.funct() can be the left operand of the assignment operator even if funct() is not returning a l-value reference.
class A
{
public:
A funct () {A x; return x;}
};
int main ()
{
A a,b; a.funct()=b;
}
In the auto generated methods for the class, there is
A& operator = (const A&);
which make a.funct() = b legal.
To forbid affectation to rvalue, you may, since C++11, write and implement
A& operator = (const A&) &; // Note the last &
so assignation would only work for lvalue.
In the code, funct should return a variable that can be assigned to.
Note that the code in funct is very dangerous too if it were to be returned by reference; the local variable x will go out of scope once the function ends and the variable returned will cause undefined behaviour as its destructor will have been called.
Your assumption is wrong. Your code is perfectly valid.
Try this code:
#include <string>
#include <iostream>
class A
{
std::string m_name;
public:
A(const std::string& name) :m_name(name) {}
A funct() { A x("intern"); return x; }
A& operator=(const A& a)
{
m_name += a.m_name;
return *this;
}
void print() { std::cout << m_name << std::endl; }
};
int main()
{
A a("A"), b("B"); (a.funct() = b).print();//prints "internB"
}

Overloading operators "=" and "+" do not work when combined in C++

#include <iostream>
using namespace std;
class A
{
public:
A(int a)
{
length = a;
}
~A(){}
friend A operator +(A& var1, A& var2);
A& operator=(A &other);
int length;
};
A operator +(A& var1, A& var2)
{
return A(var1.length + var2.length);
}
A& A::operator=(A &other)
{
length = other.length;
return *this;
}
int main()
{
A a(1);
A b(2);
A c(3);
c = a; // work
c = a + b; // does not work
cout << c.length ;
return 0;
}
In main(), c = a is successfully compiled but "c = a + b" is not.
However, in A& A::operator=(A &other), if I change (A &other) into (A other) then it works.
Can anyone help me with this case?
The simplest fix is to make your assignment overload take it's parameter by const reference.
Then the temporary returned by a + b can be used with it.
A& A::operator=(A const & other)
{
length = other.length;
return *this;
}
You'll probably want to do the same thing with your operator+ so that c = a + a + a; will work as well.
The problem is that operator + returns a temporary object
friend A operator +(A& var1, A& var2);
But a temporary object may not be bound to a non-const reference that is the type of the parameter of the assignment operator.
A& operator=(A &other);
So the compiler issues an error for statement
c = a + b;
You have three possibility.
The first one os to declare the parameter of the copy assignment operator as constant reference
A& operator=(const A &other);
It is the simplest approach.
The second one is to declare a move assignment operator instead of the copy assignment operator. In this case you explicitly need to define also a copy or move constructor. In this case instead of
c = a;
you have to write
c = std::move( a ); // work
For example
#include <iostream>
using namespace std;
class A
{
public:
A(int a)
{
length = a;
}
~A(){}
friend A operator +(A& var1, A& var2);
A& operator=(A &&other);
A( A && ) = default;
int length;
};
A operator +(A& var1, A& var2)
{
return A(var1.length + var2.length);
}
A& A::operator=(A &&other)
{
length = other.length;
return *this;
}
int main()
{
A a(1);
A b(2);
A c(3);
c = std::move( a ); // work
c = a + b; // does not work
cout << c.length ;
return 0;
}
And at last you could have the both operators simultaneously. For example
#include <iostream>
using namespace std;
class A
{
public:
A(int a)
{
length = a;
}
~A(){}
friend A operator +(A& var1, A& var2);
A& operator=(const A &other);
A& operator=(A &&other);
A( const A & ) = default;
int length;
};
A operator +(A& var1, A& var2)
{
return A(var1.length + var2.length);
}
A& A::operator=(const A &other)
{
length = other.length;
return *this;
}
A& A::operator=(A &&other)
{
length = other.length;
return *this;
}
int main()
{
A a(1);
A b(2);
A c(3);
c = a; // work
c = a + b; // does not work
cout << c.length ;
return 0;
}
In this case in statement
c = a; // work
there will be called the copy assignment operator and in statement
c = a + b; // does not work
there will be called the move assignment operator.
Of course you also may have the copy constructor and move constructor simultaneously the same way as the copy assignment operator and the move assignment operator. For your class you could all them define as defaulted.
For example
#include <iostream>
using namespace std;
class A
{
public:
A(int a)
{
length = a;
}
~A(){}
friend A operator +(A& var1, A& var2);
A& operator=(const A &other) = default;
A& operator=(A &&other) = default;
A( const A & ) = default;
A( A && ) = default;
int length;
};
A operator +(A& var1, A& var2)
{
return A(var1.length + var2.length);
}
int main()
{
A a(1);
A b(2);
A c(3);
c = a; // work
c = a + b; // does not work
cout << c.length ;
return 0;
}

Move or Named Return Value Optimization (NRVO)?

Lets say we have the following code:
std::vector<int> f()
{
std::vector<int> y;
...
return y;
}
std::vector<int> x = ...
x = f();
It seems the compiler has two approaches here:
(a) NRVO: Destruct x, then construct f() in place of x.
(b) Move: Construct f() in temp space, move f() into x, destruct f().
Is the compiler free to use either approach, according to the standard?
The compiler may NRVO into a temp space, or move construct into a temp space. From there it will move assign x.
Update:
Any time you're tempted to optimize with rvalue references, and you're not positive of the results, create yourself an example class that keeps track of its state:
constructed
default constructed
moved from
destructed
And run that class through your test. For example:
#include <iostream>
#include <cassert>
class A
{
int state_;
public:
enum {destructed = -2, moved_from, default_constructed};
A() : state_(default_constructed) {}
A(const A& a) : state_(a.state_) {}
A& operator=(const A& a) {state_ = a.state_; return *this;}
A(A&& a) : state_(a.state_) {a.state_ = moved_from;}
A& operator=(A&& a)
{state_ = a.state_; a.state_ = moved_from; return *this;}
~A() {state_ = destructed;}
explicit A(int s) : state_(s) {assert(state_ > default_constructed);}
friend
std::ostream&
operator<<(std::ostream& os, const A& a)
{
switch (a.state_)
{
case A::destructed:
os << "A is destructed\n";
break;
case A::moved_from:
os << "A is moved from\n";
break;
case A::default_constructed:
os << "A is default constructed\n";
break;
default:
os << "A = " << a.state_ << '\n';
break;
}
return os;
}
friend bool operator==(const A& x, const A& y)
{return x.state_ == y.state_;}
friend bool operator<(const A& x, const A& y)
{return x.state_ < y.state_;}
};
A&& f()
{
A y;
return std::move(y);
}
int main()
{
A a = f();
std::cout << a;
}
If it helps, put print statements in the special members that you're interested in (e.g. copy constructor, move constructor, etc.).
Btw, if this segfaults on you, don't worry. It segfaults for me too. Thus this particular design (returning an rvalue reference to a local variable) is not a good design. On your system, instead of segfaulting, it may print out "A is destructed". This would be another sign that you don't want to do this.

conversions in C++

I have this snippet of the code:
header
class A {
private:
int player;
public:
A(int initPlayer = 0);
A(const A&);
A& operator=(const A&);
~A();
void foo() const;
friend A& operator=(A& i, const A& member);
};
operator=
A& operator=(A& i, const A& member){
i(member.player);
return i;
}
and I have row in my code:
i = *pa1;
A *pa1 = new A(a2);
at the beginning i was int
how can I fix it, thanks in advance
I have an error must be non-static function
The assignment operator for a class must be a member function, not a friend.
A& operator=( const A& member){
this->player = member.player);
return *this;
}
If you want to convert an A class object to an integer, provide a named conversion function such as ToInt().
As with all your questions, this could easily have been answered by reading a C++ text book. This is the last of such questions from you I will be answering.