This question already has answers here:
Meaning of 'const' last in a function declaration of a class?
(12 answers)
Closed last year.
I'm learning C++ i saw a const after an operator function.
It doesn't make sense because the function returns the same value regardless of the const.
What's the purpose of using it?
using namespace std;
class Person {
public:
int age;
Person(int age) : age(age) {}
int operator *(int &b) const {
return b;
}
};
int main() {
Person *p = new Person(11);
int a = 19;
cout << *p * a; // prints 19
delete p;
}
A const operator behind a member function applies to the this pointer, i.e. it guarantees that the object you call this function on may not be changed by it. It's called a const-qualified member function
If you tried, in this example, to change the persons age in the openrator*(), you would get a compile error.
Related
This question already has answers here:
Is there any reason to use this->
(16 answers)
Closed last year.
res.var= this->var+obj.var;
res.var = var + obj.var;
both work same so what the benefit of using this keyword
Here is my code
#include <bits/stdc++.h>
using namespace std;
class MyClass {
public:
int var, v;
MyClass() {}
MyClass(int a, int b)
: var(a), v(b) { }
MyClass operator+(MyClass &obj) {
MyClass res;
res.var = this->var + obj.var;
res.v = v + obj.v;
return res;
}
};
int main(){
MyClass ob(12, 12);
MyClass ob1(55, 56);
MyClass res = ob + ob1;
cout << res.var << " " << res.v;
}
can anyone explain me the benefit of this keyword in operator overloading
It's there for clarity: it has absolutely no effect on the generated program.
Some folk prefer (*this). for even better symmetry.
Occasionally you do need to use this to disambiguate from a local variable or even another token; the latter can occur when working with templates and some compilers don't follow the rules properly.
Note that you should pass const MyClass& obj else anonymous temporaries can't bind to your overloaded function: an expression like ob1 + ob2 + ob3 would not compile as you have it.
This question already has answers here:
"const T &arg" vs. "T arg"
(14 answers)
What are the differences between a pointer variable and a reference variable?
(44 answers)
Closed 7 years ago.
// const objects
#include <iostream>
using namespace std;
class MyClass {
int x;
public:
MyClass(int val) : x(val) {}
const int& get() const {return x;}
};
void print (const MyClass& arg) { // Need to understand this line
cout << arg.get() << '\n';
}
int main() {
MyClass foo (10);
print(foo);
return 0;
}
I am new to C++. Need to understand what are the parameters passed in print function. If this is address then why are we passing foo is print function call.
The & in void print (const MyClass& arg) that arg is passed by reference. It is C++s way to make pointers and things a little bit easier.
References allow you to manipulate a variable inside of a function and make the results visible on the outside too. So a bit like pointers. But you don't need to explicitly get the address of the variable to do that.
The const statement is a way to prevent the described behavior. const forbids the manipulation of arg inside print.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What does the explicit keyword in C++ mean?
I do not understand the following. If I have:
class Stack{
explicit Stack(int size);
}
without the keyword explicit I would be allowed to do:
Stack s;
s = 40;
Why would I be allowed to do the above if explicit wasn't provided?? Is it because this is stack-allocation (no constructor) and C++ allows anything to be assigned to the variable unless explicit is used?
This line
s = 40;
is equivalent to
s.operator = (40);
Which tries to match the default operator = (const Stack &). If the Stack constructor is not explicit, then the following conversion is tried and succeeds:
s.operator = (Stack(40));
If the constructor is explicit then this conversion is not tried and the overload resolution fails.
hey its pretty simple .
the explicit key word only stops complier from automatic conversion of any data type to the user defined one.. it is usually used with constructor having single argument .
so in this case u are jus stopping the complier from explicit conversion
#include iostream
using namespace std;
class A
{
private:
int x;
public:
A(int a):x(a)
{}
}
int main()
{
A b=10; // this syntax can work and it will automatically add this 10 inside the
// constructor
return 0;
}
but here
class A
{
private:
int x;
public:
explicit A(int a):x(a)
{}
}
int main()
{
A b=10; // this syntax will not work here and a syntax error
return 0;
}
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Invoking a nonconst method on a member from a const method
Constant member functions are able to call non constant member functions via pointer member variables in C++, is it as expected?
Below give code snippet is compiling successfully
#include <iostream>
class S {
public:
void hi() {
std::cout << "Hi" << std::endl;
}
};
class T {
public:
T()
: s(new S())
{}
~T()
{
delete s;
}
void hi() const {
s->hi();
}
private:
S * s;
};
int main(int argc, char ** argv) {
T t;
t.hi();
return 0;
}
The behavior is correct.
That's because the pointer is const - S * s;, not the object.
For example, the following would fail:
void hi() const {
s->hi(); //OK
s = NULL; //not OK
}
Remember, you can't modify s (which is a pointer), but you can modify *s, which is the actual object.
The type of s in the const member function is S * const, not S const*, which means the pointer itself is constant, not the object the pointer is pointing to. So the object which is non-const is used to invoke non-const function, which is Standard conformant behavior.
S const * s1 = initialization1; //same as : const S *s1 = initialization1;
S * const s2 = initialization2;
s1->hi(); //error: the object is const
s1 = nullptr; //okay : the pointer is non-const
s2->hi(); //okay: the object is non-const
s2 = nullptr; //error: the pointer is const
The title basically says it all. I mainly want to do this so that I can create an object (say, a custom string object) that can initialize the parameters of other functions in other APIs. Here's an example of me trying to get a custom integer class to work:
#include <iostream>
using namespace std;
class test
{
public:
int member;
test(int i) : member(i) {}
friend int &operator=(int &i, test t);
};
int &operator=(int &i, test t)
{
return (i = t.member);
}
int main()
{
int i;
test t = 90;
cout << (i = t);
return 0;
}
Unfortunately I receive an error saying that operator= needs to be a member function. I understand the C++ standard's goal in preventing static and non-member overloads for the assignment operator from being implemented, but is there any other way to do this? Thanks for any help/suggestions!
This is not done with an assignment operator but with an overloaded typecast. This would make your main function work like expected:
#include <iostream>
using namespace std;
class test
{
public:
int member;
test(int i) : member(i) {}
operator int() const {return member;}
};
int main()
{
int i;
test t = 90;
cout << (i = t);
return 0;
}
What you are trying to do needs an conversion operator
operator int()
{
return this->member;
}
For the class you are trying to write(containing only integer members), You do not need to overload the = operator.
= operator is one of the member functions that is generated by the compiler by default for every class. Caveat is, it does a simple bit by bit copy(shallow copy) of class members, since you have only integers it should be good enough for you.
You would need to overload the = operator if you had dynamically allocated pointers as member functions, because in that case a shallow copy of those pointers would result in all the objects containing a member pointer pointing to the same dynamic memory location & if one of the object finishes it lifetime, other objects are left with a dangling pointer.
As #Tony, aptly points in out comments Shallow copy is usually bad but not always. See his comments for a scenario.
If at all you want to overload the assignment operator check out the Copy and Swap Idiom to do it right way.
You should also check out the Rule of Three.
Try this:
class test
{
public:
int member;
test(int i) : member(i) {}
operator int() {return this->member;}
};
int main(void)
{
int i;
test t = 90;
cout << (i = t);
return 0;
}
The assignment operator cannot be a friend function. The assignment operator can only be declared as a non-static member function. This is to ensure that it receives the L-value as its first operand. The same is true for the [], (), and -> operators. In your case, since int is an build-in type, you cannot use member function. You can implement operator int() to cast your user-defined type to int.