Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Classes and member variables and fucntions

Status
Not open for further replies.

danbaarts

Technical User
Dec 5, 2002
2
US
I am new to C++.

Can you access the value of a private member variable of one class from a member function of another class?

If so how? If not what are some other ways to get the value of a private member variable so it can be accessed outside of its class?

Thanks

Danny
 
Hi Danny,
We can access a private member of a claa from other class member function i fthey are declared friend functions.

To simply get the private member outside a class,write a public member function that returns the value of the private member.

S.Senthil kumar
 
You can only access private members of Class1 if Class2 is a "friend" of Class1 (which kind of ruins encapsulation) or if the Class2 "inherits" from Class1.

You can find out about inheritance and friend classes in C++ with a google search, but I think you want something simpler.

If you set Class1 up with a function returnPrivateMember(), then Class2 can call that function to get the variable.

E.g.

Class Class1
{
public:
Class1( int input ) { privateInt = input; }
int returnPrivateInt() { return privateInt; } //access to copy of private member
private:
int privateInt; //private member
};

class Class2
{
public:
Class2(): myClass1( 6 ) //initializes private Class1 with a value of 6
{ privateDouble = myClass1.returnPrivateInt(); } //assigns privateDouble with value returned by Class1 function
double returnPrivateDouble() { return privateDouble; }
private:
Class1 myClass1;
double privateDouble;
};

With such return-a-private-member functions, you can make sure the data of the class is still protected, while allowing other code to "see" the variable.
 
PS

Here's a clearer Class2

class Class2
{
public:
Class2(): myClass1( 6 ) //initializes private Class1 with a value of 6
{ privateDouble = myClass1.returnPrivateInt(); } //assigns privateDouble
//with value returned
//by Class1 function
double returnPrivateDouble() { return privateDouble; }
private:
Class1 myClass1; //initialized in constructor above
double privateDouble;
};
 
PSS I lied about inheritance giving access to private members... I had a brain fart, it gives you access to protected members...

Ummmm, I'll just shut-up now.
 
thanks so much to both of you!

your help is greatly appreciated


danny (future answer giver)
 
You didn't lie :) Otherwise this quote would have never been said

"Remember, in C++, only friends can touch your private parts"

:)

Matt
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top