i'm new to programming and we just started learning "classes". I'm going to show you an example code which i found on the internet. My question is- Are "add" and "res" constructors and how is it possible that a constructor returns a value? "X res and X add" aren't int type methods and it still returns a value(there isn't also a variable for res), so i'm really confused.. I've saw in a few posts in stackoverflow that constructors can't return a value, but then what are "X res and X add" ?
#include <iostream>
using namespace std;
class X {
int a;
int b;
public:
X (int a=7, int b=6) {
this->a = a;
this->b = b;
}
void print() {
cout << a << b;
}
X add() {
X res(a+b, a-b);
return res;
}
};
int main() {
X x;
x.add().print();
return 0;
}
Are "add" and "res" constructors?
No. add() is a member function of class X and returns X, res is a local variable inside add() with type X.
constructors can't return a value
Yes, it's right.
Are "add" and "res" constructors and how is it possible that a constructor returns a value?
No add() is a "normal" class member function, and it returns a new X instance called res, that was initialized using the X(int, int) constructor.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With