Private varialbe in class

+2 Rashed Azad · May 14, 2015
Hi,  I have a confusion you show an example of keeping the variable in private class. The example is similar  to the program below.


#include
using namespace std;
class private_variable {
    
    public:
    private_variable(int a1) { aa=a1; }
    int get_back(){ return aa; }
    private:
    int aa;
};

int main() {
    private_variable obj(10);
    cout
I was trying to practice it on my own, and I notice that it I do not write the void put_value(int b){ aa=b; } in the class instead of that write private_variable(int a1) { aa=a1; } with the constructor my program is also working fine. I know they are going to do the same thing, but can you please explain why it is safe to declare the intermediate function void put_value(int b){ aa=b; } .



#include
using namespace std;
class private_variable

{    
    public:
    private_variable(int a1) { aa=a1; }
    int get_back(){ return aa; }
    private:
    int aa;
};

int main(){
    private_variable obj(10);
    cout

Post a Reply

Replies

Oldest  Newest  Rating
+1 Michael Bradford · May 20, 2015
"but can you please explain why it is safe to declare the intermediate function void put_value(int b){ aa=b; } ." 
The reason you can do this is because the intermediate function void put_value(int b){ aa = b;} would be part of the class and therefore would have access to the private member of the class aa, IF however you declared the function OUTSIDE of the class than it would be rejected.



IF you declared the function OUTSIDE of the class and declared it as a FRIEND function it will have access to the private and protected members of the class EVEN without being a member of that class (But that is getting ahead of you a bit).
+1 Sengngy Kouch · May 15, 2015
Hi there,

I almost throw up trying to read your question, Please write your code on your software and printscreen it next time. lol


But by the way. I might be able to explain a little bit on your issue.


First of all, a Constructor constructs your object. and when you construct an object, you can give it anything.

Example:  
private_variable Tom(10). //you give Tom 10 dollars. 




and your put_value function is the setter or giver. // set your object with new value will always work.
Example:  
Tom.put_value(20);

now you make him having a total of 20, instead of 10 dollars.


Please note that, your constructor. will be   something (10);   ............ and your function will be     Tom.something(10).

and your function can only be use after your object (Tom) is created from the default constructor/ constructor.


I hope this helps!!!
  • 1

C++

107,345 followers
About

Used in many types of software including music players, video games, and many large scale applications.

Links
Moderators
Bucky Roberts Administrator