I have create a program to overload << operator for my class.
I have a doubt about the return type of the overloaded method.
When i am returning the out from the overloaded operator function the program is working fine.
But when i am not returning any thing from the function the program crashing under one condition.
In many C++ resource i have read that the return type is necessary to print operators in cascading .
Condition 1 : Passing
When i am using statement
// cout<<"\n"<<mv1<<mv2<<mv3;
Every thing is working fine. Passing without return from overloaded function.
Condition 2:Failing
When i am using statemtent
cout<<"\n"<
This i know that return was not there so the program crashed at runtime.
But the question is what made program run in Condition 1 . Even without the return statement was not present in the overloading function.
Program below
I have create a program to overload << operator for my class.
I have a doubt about the return type of the overloaded method.
When i am returning the out from the overloaded operator function the program is working fine.
But when i am not returning any thing from the function the program crashing under one condition.
In many C++ resource i have read that the return type is necessary to print operators in cascading .
Condition 1 : Passing
When i am using statement
// cout<<"\n"<<mv1<<mv2<<mv3;
Every thing is working fine. Passing without return from overloaded function.
Condition 2:Failing
When i am using statemtent
cout<<"\n"<
This i know that return was not there so the program crashed at runtime.
But the question is what made program run in Condition 1 . Even without the return statement was not present in the overloading function.
Program below
#include <iostream>
#include <stdio.h>
using namespace std;
class myvar{
private:
int var_x,var_y;
public:
friend ostream& operator<<(ostream &out,myvar n);
void setvalue(int x,int y)
{
var_x = x ;
var_y = y ;
}
};
ostream& operator<<(ostream &out,myvar n)
{
cout<<"("<<n.var_x<<","<<n.var_y<<")";
//return out;
}
int main()
{
myvar mv1,mv2,mv3;
mv1.setvalue(10,20);
mv2.setvalue(30,40);
mv3.setvalue(50,60);
//Working
// cout<<"\n"<<mv1<<mv2<<mv3;
//Not Working
// cout<<"\n"<<mv1<<mv2<<mv3<<"Hello"<<1243<<11.5;
}
This code has Undefined Behavior.
This is very bad. Usually it means that a crash will happen (but technically anything can happen).
ostream& operator<<(ostream &out,myvar n)
{
out<<"("<<n.var_x<<","<<n.var_y<<")"; // fixed cout to out.
//return out;
}
This is because you specify a return type in the function signature.
ostream& operator<<(ostream &out,myvar n)
^^^^^^^^
If your function does not contain a return keyword then your code is invalid. So for the function as defined (with the commented out return) your program will most likely crash.
If you change your code to:
void operator<<(ostream &out,myvar n)
{
out<<"("<<n.var_x<<","<<n.var_y<<")";
}
Now it will compile (be valid) and work.
But the consequence is you can not chain stream operations together.
myvar x;
// Set some value in x
// This will work fine.
std::cout << x;
// But this will fail to compile.
std::cout << x << " Another Thing";
Because the first call to operator<< returns a void the second call to operator<< does not know what to do.
So your best bet is to return the stream to allow chaining.
ostream& operator<<(ostream &out,myvar n)
{
out<<"("<<n.var_x<<","<<n.var_y<<")";
return out;
}
PS: Some space characters would be really nice to aid readability.
// This is easier to read for a human.
std::ostream& operator<<(std::ostream &out, myvar n)
{
out << "(" << n.var_x << "," << n.var_y << ")";
return out;
}
Yes, you always return the passed in ostream and probably want to pass in a const reference to the value you want outputed:
ostream& operator<<(ostream &out, const myvar& n)
{
out << "(" << n.var_x << "," << n.var_y << ")";
return out;
}
My biggest doubt is that why chaining of << in following statement
is working even without the return of out from overloaded function.
cout<<"\n"<<mv1<<mv2<<mv3;
Let's look at the following C++ code:
#include <iostream>
int main()
{
int z = 2;
class A {
public:
const int & x;
A(const int & x) : x(x) {}
void show(){
std::cout << "x=" << this->x << std::endl ;
}
} a(z);
a.show();
z = 3;
a.show();
}
The program prints: 2 and 3
It clearly shows that while inside class A x can't be modified, it merely means it's read only, because I can change it's value from outside.
Of course I can make it a copy stored inside class A, but I'm wondering if there is (or if there is a proposal?) of a way to say to class A that the member x will be truly constant instead of merely read only, with the meaning of a promise that the external code won't change it ?
To my eyes it looks like something related to the meaning of the C restrict keyword, but I've not heard of any such C++ feature yet. Do you ?
Constness is an attribute of the actual variable.
The term const int& x simply means "x is a reference to an int which it will not modify" and of course the compiler enforces this.
If you want the actual variable to which x refers to be const, simply declare it so:
#include <iostream>
int main()
{
const int z = 2; // declared const. Nothing may ever modify it
class A {
public:
const int & x;
A(const int & x) : x(x) {}
void show(){
std::cout << "x=" << this->x << std::endl ;
}
} a(z);
a.show();
z = 3; // this is a logic error, caught by the compiler.
a.show();
}
compiling correctly produces the error:
./const.cpp:41:7: error: read-only variable is not assignable
z = 3;
~ ^
1 error generated.
You're looking for D's immutable keyword, which was introduced as a new concept in that language precisely because, unfortunately, the answer is no: it does not exist in C++.
Constness in C++ does not mean immutability, but that the variable in question is read-only. It can still be modified by other parts of the program. I understand your question as to whether it's possible to enforce true immutability in a called function without knowing what the caller is doing.
Of course you can create a template wrapper class which accomplishes the task:
template <typename T>
class Immutable
{
public:
template <typename ...Args>
Immutable( Args&&...args )
: x( std::forward<Args>(args)... )
{}
operator const T &() const
{
return x;
}
private:
const T x;
};
As long as you do not reinterpret_cast or const_cast you will have truly immutable objects when you wrap them with Immutable<T>.
However, if you have a constant reference to some object, there is no way to tell, if some other part of the program has a non-constant access to the object. In fact, the underlying object might be a global or static variable, that you have read-only access to, but functions you call might still modify it.
This cannot happen with Immutable<T> object. However, using Immutable<T> might impose an extra copy operation on you. You need to judge yourself if you can live with that and if the cost justifies the gain.
Having a function require an const Immutable<Something> & instead of const Something & as an argument affects the calling code. A copy operation might be triggered. Alternatively, you can ask for an Immutable<Something> & without the const. Then no accidental copies will be triggered, but the calling code must pass a reference to Immutable<Something> object. And rightly so, because if the caller received a const & as an argument then the caller does not know, whether the object might get modified by someone else in the program. The caller has to create the object itself or require an immutable object to be passed to it as a reference.
Your original question
Here's your original problem with Immutable<int> & instead of const int &.
#include <iostream>
int main()
{
Immutable<int> z = 2;
class A {
public:
const Immutable<int> & x;
A(Immutable<int> & x) : x(x) {}
void show(){
std::cout << "x=" << this->x << std::endl ;
}
} a(z);
a.show();
//z = 3; // this would fail
a.show();
}
An other example
Here's how it works: If you write
void printAndIncrementAndPrint( int & i1, const int & i2 )
{
std::cout << i2 << std::endl;
++i1;
std::cout << i2 << std::endl;
}
int main()
{
int i = 0;
printAndIncrementAndPrint( i, i );
}
then it will print
0
1
into the console. If you replace the second argument of printAndIncrementAndPrint() with const Immutable<int> & i2 and keep the rest the same, then a copy will be triggered and it will print
0
0
to the console. You cannot pass and Immutable<int> to the function and a int & to the same underlying data without breaking the typesystem using const_cast or reinterpret_cast.
I think this is a design problem for the programmers, not the language. A const variable means for any user of that variable, they should not change the value of that variable. Our compiler is smart enough to help us make sure of that. So A is a user of z and if you want A know that A::x references to a const variable, then you should make z a const int. The const reference is just to keep the contract between the user and the provider.
I'm trying to understand how this type of function works and how you would use it.
I assume there's some class we'll call it test.
class Test {
}
I saw this type of function in a header file and I'm trying to figure out what it does. And how to use it properly.
Test& testFunction();
Appreciate the help.
What's in front of the function name is the type that the function will return. In this case, testFunction is returning a Test object. The & in this case (reference) means that it will return a Test-reference. This is important if you wish to modify the returned object when you call the function. Or use it in some way not possible with "return-by-value".
Your code doesn't tell us much about what you're going to be doing with the return value, but here is a good example that's used quite commonly:
Test & T::f() {
// do something
return *this;
}
*this here is the actual object on which its method .f is being called. What's special here is that since we are returning a reference, we can chain calls while maintaining the original object. *this will be the same *this every time. With return-by-value we aren't able to do this. For example:
By reference:
Test & T::f() {
this->x++;
return *this;
}
int main() {
Test t;
t.x = 5;
t.f().f();
std::cout << t.x; // 7 as we expect
}
By value:
Test T::f() { ... } // notice the omission of &
int main() {
Test t;
t.x = 5;
t.f().f();
std::cout << t.x; // 6
}
t is changed only once because the object is lost on the next call.
Some hours ago I read this question in which the user initialized a const object as
const QList warnings = QList() << 0 << 3 << 7;
Indeed, this expression somehow hurt me because going against the concepts I have of const and of overloading operator<<.
I tried to define an operator<< possibly allowing for the mentioned expression and here is what I got:
typedef vector<int> Vect;
Vect operator<<(Vect v, const int i){ //ByVal v, This way it works, but at which cost?
v.push_back(i); //v is copied at every call!
return v;
};
//Here is where I build the object
const Vect const_vect = Vect() << 1 << 2;
//it works fine but I see massive overhead due to copies..#_#
//Just for testing
int main() {
for(auto e = const_vect.begin(); e!=const_vect.end() ; ++e){
cout << *e << " ";
}
return 0;
}
The previous code (which is also here) works fine.
The following, on the other hand, is the expression I would have expected from the definition of operator<<:
Vect& operator<<(Vect& v, const int i){ //ByRef v<-this I would have expected;
v.push_back(i); //however it can't work because receives and
return v; //returns reference to temporary object.
};
My question is: what am I missing? is the operator<< defined in QList differently implemented from mine, in particular, can it receive and return ByRef?
Secondly, is perhaps the aforementioned a standard procedure to initialize complex const objects?
Thirdly (maybe inconvenient), how would such an expression handled by the compiler? what is done at compile-time and what at run-time?
Is there a (more or less at least) standard int class for c++?
If not so, is it planned for say C++13 and if not so, is there any special reasons?
OOP design would benefit from it I guess, like for example it would be nice to have an assignment operator in a custom class that returns an int:
int i=myclass;
and not
int i=myclass.getInt();
OK, there are a lot of examples where it could be useful, why doesn't it exist (if it doesn't)?
It is for dead reckoning and other lag-compensating schemes and treating those values as 'normal' variables will be nice, hopefully anyway!.
it would be nice to have an assignment operator in a custom class that returns an int
You can do that with a conversion operator:
class myclass {
int i;
public:
myclass() : i(42) {}
// Allows implicit conversion to "int".
operator int() {return i;}
};
myclass m;
int i = m;
You should usually avoid this, as the extra implicit conversions can introduce ambiguities, or hide category errors that would otherwise be caught by the type system. In C++11, you can prevent implicit conversion by declaring the operator explicit; then the class can be used to initialise the target type, but won't be converted implicitly:
int i(m); // OK, explicit conversion
i = m; // Error, implicit conversion
If you want to allow your class to implicitly convert to int, you can use an implicit conversion operator (operator int()), but generally speaking implicit conversions cause more problems and debugging than they solve in ease of use.
If your class models an int, then the conversion operator solution presented by other answers is fine, I guess. However, what does your myclass model?
What does it mean to get an integer out of it?
That's what you should be thinking about, and then you should come to the conclusion that it's most likely meaningless to get an integer without any information what it represents.
Take std::vector<T>::size() as an example. It returns an integer. Should std::vector<T> be convertible to an integer for that reason? I don't think so. Should the method be called getInt()? Again, I don't think so. What do you expect from a method called getInt()? From the name alone, you learn nothing about what it returns. Also, it's not the only method that returns an integer, there's capacity() too.
Implement operator int () for your class
This can be realized by the cast operator. E.g:
class MyClass {
private:
int someint;
public:
operator const int() {
return this->someint;
}
}
No there isn't any standard int class. For things such as BigDecimal you can look at Is there a C++ equivalent to Java's BigDecimal?
As for int, if you really need it, you can create your own. I have never come across an instance where I needed an Integer class.
No, and there won't be any. What you want to do can be done with conversion operator:
#include <iostream>
struct foo {
int x;
foo(int x) : x(x) {}
operator int() { return x; }
};
int main() {
foo x(42);
int y(x);
std::cout << y;
}
No, and there probably won't be.
int i=myclass;
This is covered by conversion operators:
struct MyClass {
operator int() {
return v;
}
int v;
} myclass = {2};
int i = myclass; // i = 2
Not everything has to be 'object oriented'. C++ offers other options.
There are obvious reasons to have a class for int, because int by itself does not allow for the absence of any value. Take for instance a JSON message. It can contain the definition for an object named “foo”, and an integer named “bar”, for example:
{"foo": {"bar": 0}}
Which has the meaning that “bar" is equal to 0 (zero), but if you omit “bar”, like this:
{"foo": {}}
Now it takes on the meaning that “bar” is non-existent, which is a completely different meaning and cannot be represented by int alone. In the old days, if this situation arose, some programmers would use a separate flag, or use a specific integer value to signify that the value was not supplied, or undefined, or non-existent. But whatever you call it, a better way is to have a class for integer which defines the functionality and makes it reusable and consistent.
Another case would be a database table that has an integer column added some time after it’s creation. Records that were added prior to when the new column was added will return null, meaning no value present, and records added after the column’s creation would return a value. You may need to take a different action for null value vs. 0 (zero).
So here's the beginnings of what a class for int or string might look like. But before we get to the code, let's look at the usage as that is why you would create the class in the first place, to make your life easier in the long run.
int main(int argc, char **argv) {
xString name;
xInt age;
std::cout<< "before assignment:" << std::endl;
std::cout<< "name is " << name << std::endl;
std::cout<< "age is " << age << std::endl;
// some data collection/transfer occurs
age = 32;
name = "john";
// data validation
if (name.isNull()) {
throw std::runtime_error("name was not supplied");
}
if (age.isNull()) {
throw std::runtime_error("age was not supplied");
}
// data output
std::cout<< std::endl;
std::cout<< "after assignment:" << std::endl;
std::cout<< "name is " << name << std::endl;
std::cout<< "age is " << age << std::endl;
return 0;
}
Here is the sample output from the program:
before assignment:
name is null
age is null
after assignment:
name is john
age is 32
Note that when the instance of the xInt class has not been assigned a value, the << operator automatically prints "null" instead of zero, and the same applies to xString for name. What you do here is totally up to you. For instance, you might decide to print nothing instead of printing “null”. Also, for the sake of brevity, I've hard coded the assignments. In the real world, you would be gathering/parsing data from a file or client connection, where that process would either set (or not set) the data values according to what is found in the input data. And of course, this program won't actually ever throw the runtime exceptions, but I put them there to give you a flavor of how you might throw the errors. So, one might say, well, why don't you just throw the exception in your data collection process? Well, the answer to that is, with the eXtended class variables (xInt & xString), we can write a generic, reusable, data gathering process and then just examine the data that is returned in our business logic where we can then throw appropriate errors based on what we find.
Ok, so here's the class code to go with the above main method:
#include <iostream>
#include <string>
class xInt {
private:
int _value=0;
bool _isNull=true;
public:
xInt(){}
xInt(int value) {
_value=value;
_isNull=false;
}
bool isNull(){return _isNull;}
int value() {return _value;}
void unset() {
_value=0;
_isNull=true;
}
friend std::ostream& operator<<(std::ostream& os, const xInt& i) {
if (i._isNull) {
os << "null";
} else {
os << i._value;
}
return os;
}
xInt& operator=(int value) {
_value=value;
_isNull=false;
return *this;
}
operator const int() {
return _value;
}
};
class xString {
private:
std::string _value;
bool _isNull=true;
public:
xString(){}
xString(int value) {
_value=value;
_isNull=false;
}
bool isNull() {return _isNull;}
std::string value() {return _value;}
void unset() {
_value.clear();
_isNull=true;
}
friend std::ostream& operator<<(std::ostream& os, const xString& str) {
if (str._isNull) {
os << "null";
} else {
os << str._value;
}
return os;
}
xString& operator<<(std::ostream& os) {
os << _value;
return *this;
}
xString& operator=(std::string value) {
_value.assign(value);
_isNull=false;
return *this;
}
operator const std::string() {
return _value;
}
};
Some might say, wow, that's pretty ugly compared to just saying int or string, and yes, I agree that it's pretty wordy, but remember, you only write the base class once, and then from then on, your code that you're reading and writing every day would look more like the main method that we first looked at, and that is very concise and to the point, agreed? Next you'll want to learn how to build shared libraries so you can put all these generic classes and functionality into a re-usable .dll or .so so that you're only compiling the business logic, not the entire universe. :)
There's no reason to have one, and so there won't be any.
Your cast operator should realize this
An example
class MyClass {
private:
int someint;
public:
operator const int() {
return this->someint;
}
}