Home > Software engineering >  Return class object with member variable
Return class object with member variable

Time:02-18

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

CodePudding user response:

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.

  • Related