specbk
specbk

Reputation: 89

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;
}

Upvotes: 3

Views: 58

Answers (4)

fgksgf
fgksgf

Reputation: 29

what are "X res and X add" ?

X res is means that res is an object of class X; add is the name of a member function of the class X, and it can return an object of class X.

Upvotes: 1

BlackMamba
BlackMamba

Reputation: 10252

A class constructor is a special member function of a class that is executed whenever we create new objects of that class.

A constructor will have exact same name as the class and it does not have any return type at all, not even void. Constructors can be very useful for setting initial values for certain member variables.

So add and print not constructor. just X (int a=7, int b=6) { this->a = a; this->b = b; } is constructor.

Upvotes: 0

πάντα ῥεῖ
πάντα ῥεῖ

Reputation: 1

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.

Upvotes: 2

songyuanyao
songyuanyao

Reputation: 173044

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.

Upvotes: 3

Related Questions