how do i access data member from other class

D

diadia

when i write two classes as follow .

compiler tell me that i can't access private number from other class

but if types of two classes are the same it don't have error message ? why?

class schema
{

private:
string name;
int age;
public:
schema(string n,int a):name(n),age(a){}

};


class data
{
private:
string str;
int num;
public:
data(int n,string s):num(n),str(s){}
data(){};

//error ! access private member from other class
void gets(const schema &s){str = s.name ; num = s.age ;}

// ok it can work,but why? it's also private member
void getd(const data &s) { str = s.str ; num = s.num;}
void put(){cout<<str<<num;}

};
 
M

Marc Schellens

diadia said:
when i write two classes as follow .

compiler tell me that i can't access private number from other class

but if types of two classes are the same it don't have error message ? why?

class schema
{

private:
string name;
int age;
public:
schema(string n,int a):name(n),age(a){}

};


class data
{
private:
string str;
int num;
public:
data(int n,string s):num(n),str(s){}
data(){};

//error ! access private member from other class
void gets(const schema &s){str = s.name ; num = s.age ;}

// ok it can work,but why? it's also private member
void getd(const data &s) { str = s.str ; num = s.num;}
void put(){cout<<str<<num;}

};

Note that access permissions are based on types not on
individual objects.
HDH,
marc
 
B

Brandon McCombs

diadia said:
when i write two classes as follow .

compiler tell me that i can't access private number from other class

but if types of two classes are the same it don't have error message ? why?

a class can access it's own private data members from within the class. A class can not access
another class's private membes..thats the very reason you would make them private: so that only that
class that owns the private members can access them. If you want to be able to acess them from
outside that classs you need to create a function that returns those values and then save those
values to variables. If u want to save the values to private members of another class then you need
to also create a function in that "destination" class to set those variables within the class.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,150
Messages
2,570,853
Members
47,394
Latest member
Olekdev

Latest Threads

Top