Home > Back-end >  How to return struct from class where it is defined?
How to return struct from class where it is defined?

Time:12-08

I want to return a copy of struct from public class function, and i define this struct inside this class as a private member.

Is it possible to return this structure of any other type of custom data?

Consider this simple example:

class Test {
private:
    struct sTest {
        int i = 1;
    }_sTest;
public:
    sTest GetStruct() {
        return _sTest;
    }
};

then after i create object of this class:

Test cTest;

how can i call

 cTest.GetStruct()

to get

 _sTest

?

CodePudding user response:

You can use auto to store the object.

Following is sample code. See it here in action:

#include <iostream>
using namespace std;

class Test {
private:
    struct sTest {
        int i = 1;
    }_sTest;
public:
    sTest GetStruct() {
        return _sTest;
    }
};



int main()
{
    Test a;
    auto obj = a.GetStruct();
    
    cout<< obj.i <<"\nDone!!!\n";
    return 0;
}

Output:

1
Done!!!

Note: It is fine on other compilers also. Check here on other compilers also.

CodePudding user response:

Since the private class is not accessible from the class Test outside, use the keyword auto.

auto test = cTest.GetStruct();

CodePudding user response:

Yes, it is perfectly safe. It is like any other type of data. With auto you are just telling the compiler to guess which kind of variable would be.

  • Related