Kar Wai Kar Wai - 3 months ago 24
C++ Question

How to return private char array from member function?

How can i return the private char "n" from the member function to the main function?

#include <iostream>
using namespace std;
class TEST
{
char n[10];
public:
char getname()
{
cout<<"what's your name?:";
cin.getline(n,10);
return n;
}
};
int main()
{ char name[10];
TEST obj;
name[10]=obj.getname();
cout<<"Name :"<<name;
}

Answer

private or public is not matter. your problem is return char instead of char*.

I suggest you to use string instead of char array.

#include <iostream>
using namespace std;
class TEST
{
    char n[10];
public:
    char* getname()
    {
        cout<<"what's your name?:";
        cin.getline(n,10);
        return n;
    }
};
int main()
{   
    char* name;
    TEST obj;
    name = obj.getname();
    cout<<"Name :"<<name;
}