Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

methods/constructors and their return values

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;
}
like image 682
specbk Avatar asked Apr 01 '26 20:04

specbk


2 Answers

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.

like image 60
songyuanyao Avatar answered Apr 03 '26 16:04

songyuanyao


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.

like image 23
πάντα ῥεῖ Avatar answered Apr 03 '26 16:04

πάντα ῥεῖ



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!