Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return class object with member variable

Why the function test() works even I'm not returning a Base class ? What happens with the compilation ? Can someone explain me ?

#include <iostream>

class Base {
public:
    Base(){}
    Base(int val): _val(val){};
    ~Base(){};

Base test(int n){
    return (n);
}

int &operator *() { return (_val); };

private:
    int _val;

};


int main()
{
    Base base;
    Base a;

    a = base.test(42);
    std::cout << *a << std::endl;

    return (0);
}
like image 517
Myno Avatar asked Jun 19 '26 21:06

Myno


1 Answers

You declared a constructor that takes in an int, and you declared that test(int n) should always return a Base class. The compiler knows that in order to create a Base object you need either nothing (default constructor) or an int, so it creates an object using the constructor that takes an int an returns that.

If you wanted to, you could be explicit about it and do something like the following and get the exact same behaviour:

Base test(int n){
    return Base(n);
}

In short, n is implicitly cast to a Base object, as you declared a constructor that requires only an int.

like image 89
Alfonso Castillo Avatar answered Jun 21 '26 13:06

Alfonso Castillo



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!