How can i return the private char "n" from the member function to the main function?
You can return pointer to first element of character array which is under private
label in your class. For it, you need to change the function definition of your getname
function to char *getname()
.
Also, i would like to point out some error you have made in main
function. Have a look at my version:
#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()
{
TEST obj;
char *name = obj.getname();
cout<<"Name :"<<name;
}
But it is not a good practice to return a reference or pointer to private member of your class. Exposing any of your internal implementation details is potentially a violation of encapsulation. Instead of providing access to private data members of a class, you can define member functions which will perform desired operation on your private data members.
Also, try to avoid using using namespace
.