-
Fed up of a concept in c++
Hello friends ,
I am learning c++ and am a n00b in c++ , for one month i am trying to understand a concept but unable to , here it is :
when we create a class like:
Code:
class daemon{
int data;
public:
void _function(){}
}
now i want to ask that if we create a object with in the class why _function inside class can enter private data of that object too ?? it has only access to pvt data of that class but why objects too??
as you all know that i am a n00b , please teach me as a n00b i'll be yours debtor if you can solve my this problem !!
-
Re: Fed up of a concept in c++
Possible you can rephrase the question? Maybe provide an example.
-
Re: Fed up of a concept in c++
I'm not sure I understand your question. Objects are just instances of classes. A class is to an object what Ford Fiesta is to the car parked across the street.
Objects can, of course, manipulate their own data, private or not. If an object could not reach its own data, then how would it be reached?
-
Re: Fed up of a concept in c++
your question is not very clear, but the 'private' only means that it cannot be accesed from outside the class. Functions inside the class, no matter if they may be private or public, can access anything inside the class. The private, public and protected do not limit the other members of the same class, but limit how they may be acessed from outside the class
access premission
public: everyting inside class, friend classes, outside of class
protected: everyting inside class, friend classes
private: everyting inside class
There is not way to deny acces of things inside the same class, like _function, from the other memebrs of that class, like the int.
-
Re: Fed up of a concept in c++
Quote:
Originally Posted by bovinedragon
your question is not very clear, but the 'private' only means that it cannot be accesed from outside the class. Functions inside the class, no matter if they may be private or public, can access anything inside the class. The private, public and protected do not limit the other members of the same class, but limit how they may be acessed from outside the class
access premission
public: everyting inside class, friend classes, outside of class
protected: everyting inside class, friend classes
private: everyting inside class
There is not way to deny acces of things inside the same class, like _function, from the other memebrs of that class, like the int.
Actually, friend classes can access private data the same way as a friend function can. And derived classes can access public and protected data members as well. (Public, Protected, and Private inheritance apply to how the derived sees the members)
And as far as the question of the post, I think he means this.
Code:
class daemon
{
private:
int Value;
public:
void _Function()
{
daemon objInside;
objInside.Value = 100;
}
// Static Members can do the same thing
static void _Function2()
{
daemon objInside;
objInside.Value = 100;
}
};
-
Re: Fed up of a concept in c++
Quote:
Originally Posted by JamesSchumacher
Actually, friend classes can access private data the same way as a friend function can. And derived classes can access public and protected data members as well. (Public, Protected, and Private inheritance apply to how the derived sees the members)
And as far as the question of the post, I think he means this.
Code:
class daemon
{
private:
int Value;
public:
void _Function()
{
daemon objInside;
objInside.Value = 100;
}
// Static Members can do the same thing
static void _Function2()
{
daemon objInside;
objInside.Value = 100;
}
};
Thanks bro you're right i meant same thing , can you explain this how its done ?? why _function can access objects private data of objInside , when it has only access to it class pvt data .
thanks!!!
-
Re: Fed up of a concept in c++
An object can access private data in an object of the same class, private or otherwise. That's just the way it is. Private restricts data by class, not by object.
-
Re: Fed up of a concept in c++
"Private restricts data by class, not by object." -> unable to understand this line!
-
Re: Fed up of a concept in c++
Quote:
Private restricts data by class, not by object.
And perhaps it is a bit terse; it makes sense to those of us already familiar with the subject.
private (or protected) access is applied across all instances of a class, not just to (or within) a particular instance.
When you substitute the word object for 'instance of a class' it may be a little clearer.
Essentially, its what the posted example code in JamesSchumacher illustrated.
Put another way, if you create an instance of a class while in a function of that class, as that code does, access to private data in the new, temporary instance is permitted because the restriction applies to the class, not to the instance of the class upon which the original function call was made.
This restriction isn't intended to provide security. The idea of private and protected members and functions is that of declaring what is internal to the workings of the class, and (for public) what is external (or what is intended for application code to use and access).
One (of many) way(s) to view the notion of objects is that of the black box component. I happen to be an electronics hobbyist, and I create gadgets for various purposes. The outer box of whatever device I create may have a knob or two, a switch, maybe a gauge, possibly some jacks for input, output and power. These are exposed to the 'user' of the gadget, and what I guarantee is for their use.
Internally there will be any number of components, wires, interconnections, possibly other knobs which I set when I created the device. These are not exposed to the user, because I don't guarantee they can be of any use in the otherwise normal functioning of the device. If unskilled users were to meddle with the internal wiring, or adjust the internal knobs which calibrate the device, its operation would no longer be what I could guarantee. They would be, in essence, modifying my design.
This analogy breaks down a bit, though, because it DOES suggest the privacy of the internal components is by instance (privacy for each copy of this device I create, such that devices couldn't 'see' into each other). In classes, this isn't the case, yet the overall sense of what is kept internal (private and protected) or external (public) is the thrust behind using these features in C++. It helps create objects that have clearly defined usage, while having complex internal workings, making the object more like a device or component than just a bunch of code.
Since the focus isn't with regard to security, there's little reason to impose the privacy restriction of various instances against each other. Doing so may have even been considered an impediment, because certainly we see that instances of a class may have reason to work directly with each other. It is the privacy restriction of other code that is of importance.
-
Re: Fed up of a concept in c++
JVene gave a good explanation.
I'll try to give another one.
Carefully note that "object" means "class instance".
The C++ access rights model is different from the SmallTalk one, and is partially due to a different apprehension of relationship between methods and objects.
In SmallTalk methods are members of objects, tied to a specific object. They're actors from inside the object.
In SmallTalk, a method is a little daemon living inside the black box. It doesn't cooperate with any high level entity. It lives with the specific object only.
In C++ methods are members of classes. In C++, methods are actors, living outside of objects, and are separate entities, though the principle of class allows one to put together objects and methods.
Analogy: Electricity provided to every house is counted with sealed counters (at least in France). Access to users is forbidden. These counters are owned by EDF (Electricité De France), and only EDF employees are allowed to open these.
Counters are C++ objects.
EDF employees are actors allowed to access these objects.
They don't live inside the black box. They live outside it, and can act on many of them.
Consequences.
In SmallTalk, the notion of static method doesn't exist... In C++, it does.
In SmallTalk, methods (the little daemons) are restricted to using their object. They cannot access private parts of other instances of the same class!
In C++, methods can access the inside of all objects of the class. Whenever a method gets a reference to ANY object of that class (through a global variable, a parameter, the this pointer, creation inside it, creation through a call to another function, etc.), it can access to its internal details.
The C++ approach, has many advantages. Actually, the SmallTalk approach is pretty, simple, cute, but doesn't work very well in real world.
Relevant example:
Assume you want to write a BigNum class. BigNums have an internal representation that only mathematicians can understand and exposing it to users is useless, as they only want to add, substract, multiply, divide and compare numbers.
-- SmallTalk --
In SmallTalk, where could we put the Add() method?
As a member of every object? But... If to add two numbers, there are TWO objects involved. The daemon inside the first object cannot access to the data inside the second object!
The daemons need to communicate somehow! Unfortunately, daemons have no telepathic powers. They're very lonely creatures, and they don't like to cooperate.
When cooperating, they need to do so through high level human language.
So, to add two numbers, in SmallTalk, there must be a hole in every number, through which the daemon can publically communicate (i.e. some public methods giving access to internal implementation details), so that daemons can communicate their data. The daemon makes no difference between human people and other daemons... They're very self centered, and, for them, everything outside of their little box is "the outside", including other daemons of the same specy.
That's a problem: Your black box is not closed anymore.
Second problem: There's an assymetry. One of the two daemons must start the communication, and must do part, or all, the calculus, and must build a new number...
Now, when someone wants to add two numbers, he must ask to one daemon, through a public interface, to adds itself to the other daemon... Then, they start their communication, and the first daemon produces a new number.
-- C++ --
In C++, where could we put the Add() method?
As a member of the class!
As a friend overloaded operator+ (friend functions, conceptually, are members of the class), or a Add() static method.
This method is a highly skilled employee, with a math degree, hired by the numbers objects corp., member of this corp., who knows the internal details that share all numbers, and has a key that opens all these numbers.
He is familiar with all the numbers, and like them all equally. He is not bound to a particular number.
When someone needs to add two numbers, he asks to this employee, who serves everybody who has bought two numbers or more, to add the two numbers.
The employee comes, open the two numbers with a key, look at the internal details (i.e. access private data or invoke private methods), and generate a fresh new number.
About virtual methods: A virtual method is nothing more than an employee whose telephone number is written on the object and who is entirely responsible of maintaining this object (he can be called whenever anybody who uses the object needs his service), but is highly skilled and able to access any other object, though he may have specific knowledge about specific types of these objects.
I'm not sure it helps, but at least, reading my post should have been entertaining.
-
Re: Fed up of a concept in c++
Thanksssssssssss a lot friends , i got the concept , btw i would like to tell you guyz that soon i'll be shifting to visual c++ soon !!
-
Re: Fed up of a concept in c++
I am almost giving up , again got confused cause always my mind stop at the concept of object s. while learning other things of c++ .
here is visualization of my problem!
http://img247.imageshack.us/img247/6821/untitledee6.gif
please start reading it from bottom!!
-
Re: Fed up of a concept in c++
It seams that you still don't understand the difference between a class and an instance of a class.
The class can be seen as a set of rules to manipulate the data ( state ) of instances of that class ( objects ).
In your example both objects are of type mammal so both objects know the rules how to manipulate mammals.
C++ allowes a mammal to manipulate mammals, no matter if it is the same instance or another, it trusts that they always play according to the rules.
And then, I can't even imagine how a language that doesn't allow that would implement something like a copy constructor, if an object can't access all the data of another object of the same type.
Kurt
-
Re: Fed up of a concept in c++
Classes are a way to localize all the state (data) and services (typically member functions) associated with a cohesive concept. The main idea is to organize things so that when changes to the concept or abstraction occur (as is inevitable), it will be possible to go to one place to make the necessary modifications.
To a programmer, an object is a region of storage with associated semantics. To a designer, an object is any identifiable component in the problem domain.
As an analogy, consider a home. A home is like an object since it has state (whether the lights are on, ambient temperature, and so on) and it provides services (a button that opens the garage door, a thermostat that controls the temperature, an alarm system that detects intruders, and so on). To carry the home metaphor a bit further, a blueprint for a home is like a class since a blueprint defines the characteristics of a group of similar homes.
-
Re: Fed up of a concept in c++
Actually i understands the rules but let me divide my question :-
Inside the class (class definition ) you have (its you! , not methods, cause member methods has always access to its pvt data , whether you're outside or not) access to pvt data .
so that you can access pvt data of the object of same class too (cause you're inside the class definition).
in my questions please always note the position where you're (outside the class, inside class definition ,etc)
when you're are outside the class -> you don't have access to private data (cause you're out side the class definition and you've declared it in main function or where ever) , so that you can't access the object too? (cause it is inherited by the rules of his class)
i would feel great if one of you can teach me or clear my confusion by a animation or by an image!
Thansssssssssssssssssss!!
-
Re: Fed up of a concept in c++
Quote:
Originally Posted by daemonakadevil
From outside the class you can't enter the pvt data of that that class but inside you can
In a general context I would understand that as trying to access protected (data)members of an instance of a class. Just as I have shown in my previous example.
Quote:
Originally Posted by daemonakadevil
I want to ask that which syntax to use to enter pvt data of class from outside so compiler will give me error that you can't enter pvt data of that class , not the object of that class.
Now you are talking about data that belongs to the class but not to an instance of a class.
So I guess that you mean private static data.
Code:
class Test {
private: // this time using the private keyword
static int priv_stat_int;
public:
void set_priv(int v );
static void stat_set_priv( int v );
};
int Test::priv_stat_int = 0; // initialisation
void Test::set_priv(int v ) {
priv_stat_int = v; // Ok inside the scope of Test
}
void Test::stat_set_priv( int v ){
priv_stat_int = v; // Ok inside the scope of Test
}
int main() {
Test a;
Test::priv_stat_int = 0; // Error outside of Test ( the scope is ::main )
a.priv_stat_int = 0; // Error outside of Test
a.set_priv(5); // Ok
Test::stat_set_priv(5); // Ok
a.stat_set_priv(5); // Ok
}
But then you are talking about entering data and not accessing data. Are you talking about readonly data ? ( const data ).
Kurt
-
Re: Fed up of a concept in c++
ok thanks for answering bro , can you please tell me that what does this means :-
In books its written that From outside the class you can't enter the pvt data of that that class but inside you can
I want to ask that which syntax to use to enter pvt data of class from outside so compiler will give me error that you can't enter pvt data of that class , not the object of that class.
-
Re: Fed up of a concept in c++
Quote:
I want to ask that which syntax to use to enter pvt data of class from outside so compiler will give me error that you can't enter pvt data of that class , not the object of that class.
Place your data under private access (or protected, but usually private is the right choice). In ZuK's example, this was done without explicitly using the private keyword as private access is the default for classes declared with the class keyword.
-
Re: Fed up of a concept in c++
Sh... I have done it again. I've edited my previous post and not added a new reply.
Sorry.
Kurt
-
Re: Fed up of a concept in c++
But then you are talking about entering data and not accessing data.
whats the difference btw entering & accessing data of class?
-
Re: Fed up of a concept in c++
Quote:
Originally Posted by daemonakadevil
But then you are talking about entering data and not accessing data.
whats the difference btw entering & accessing data of class?
From outside the scope of a class you cannot access private data ( or private member functions ) -> you can't read it or write it.
By entering data I would understand to change the data ( just write ).
Kurt
-
Re: Fed up of a concept in c++
So that means While you're inside the class (for me its while defining class or inside the class definition) you can access the pvt data of class and that's why you can access & enter the pvt data of objects of same class too cause they all are instances of the same class.
its all about your position that where you're declaring instances of classes inside the class or outside?
Bro please don't refuse, can you give me Y!M (so can talk to you there)??
thanks!!
-
Re: Fed up of a concept in c++
Quote:
Originally Posted by daemonakadevil
its all about your position that where you're declaring instances of classes inside the class or outside?
No it has nothing to do with where you create the instances.
It only depends on where you try to access the private members.
True. if you create an instance of a class inside the scope of that class then you can access its private data too but that is just because then the access happens from insde the scope of that class.
Quote:
Originally Posted by daemonakadevil
Bro please don't refuse, can you give me Y!M (so can talk to you there)??
Sorry. I don't understand
Kurt
-
Re: Fed up of a concept in c++
Quote:
Originally Posted by daemonakadevil
you're inside the class (for me its while defining class or inside the class definition)
Guess now I understand your mistake.
Inside or outside of the class has nothing to do with the physical position of the code. It's a matter of the scope of the code.
Maybe somebody can explain to you the meaning of scope. Guess that my english is not good enough to do that.
Kurt
-
Re: Fed up of a concept in c++
ZuK : Sorry. I don't understand
I mean can you please give me your yahoo mail so can talk on yahoo messenger !
-
Re: Fed up of a concept in c++
Quote:
Originally Posted by daemonakadevil
ZuK : Sorry. I don't understand
I don't know what there is to understand beyond the obvious.
1) Class members with access level as private means that only the class itself can access these private members.
2) Class members with access level as protected means that the class and derived classes have access to those protected members.
3) Class members with access level as public means that anyone can access those public members.
Given this, what is it that you are not understanding?
Regards,
Paul McKenzie
-
Re: Fed up of a concept in c++
Quote:
Originally Posted by Paul McKenzie
Quote:
Originally Posted by daemonakadevil
ZuK : Sorry. I don't understand
I meant what zuk has written in his 2nd or third last post !
-
Re: Fed up of a concept in c++
Quote:
Originally Posted by ZuK
Guess now I understand your mistake.
Inside or outside of the class has nothing to do with the physical position of the code. It's a matter of the scope of the code.
Maybe somebody can explain to you the meaning of scope. Guess that my english is not good enough to do that.
Kurt
Paul McKenzie , can you teach me what he wants teach me in this quote pf zuk!
-
Re: Fed up of a concept in c++
daemonakadevil:
I empathize. Most of us have been at this point in our study at one point, but for some of us it's been many years (for myself since 1987), with respect to the study of C++. We take these understandings for granted, to the point that when it comes to explaining them to someone new to the study, we have some trouble reminding ourselves to detail the basics - they are second nature to us.
When you've been writing phrases like "inside the class" or "outside the class" you are, rather colloquially, referring to the concept of scope - but without much of the understand that scope means to those of us familiar with these concepts, yet 'too' familiar to be able to articulate them meaningfully to you. Let me try....
Scope from ancient times (before objects) :)
Code:
int main(int, char **)
{
int d = function( 10 );
return 0;
}
int function(int b)
{
int z = b * 5;
return z;
}
This trivial, perhaps useless example of a function, uses a local variable z and a parameter b.
In main, where execution begins, BEFORE 'function' is called, the variables in function z have no scope. The function has not executed, so this seems obvious.
When main begins execution (you might think the execution pointer of the CPU has entered inside the opening brace of the function), the variable d will have scope. If you want to get microscopic about this, it gains scope once the CPU has executed the code which gave it room on the stack.
Now, let's assume that execution proceeds at the microscopically slow pace of a debugger we are manually stepping into 'function'. Now, the point of execution reached the line where z = b * 5 and has just executed it.
At this point z is said to be 'in scope'. It has space in memory (the stack), it can be accessed, used, written to, etc.
Note, however, that while the point of execution is 'inside function', the variable d, from the main function, is NOT in scope.
From 'inside' the scope of 'function' we can't reach or use d from the main function. It is not within the scope of the current point of execution.
Now, b, is also in scope. It's space was prepared as a parameter to the function, we can use it, access it, etc.
Note one property here. Although d, from the main function, is not in scope while the point of execution is inside 'function', it's space has not been affected. It exists, in that space was set aside for it before 'function' was called, and that space has not been relinquished. My point is, just because space for something has been allocated doesn't mean it is in scope.
This is why you're thinking in terms of "inside" or "outside" when you wrote earlier about privacy, which I'll get to shortly. Scope does seem to suggest the notion of a 'space' in which things exist, and if you're inside that space they are within scope, but if you're outside that space they are not.
In this previous example, when 'function' returns, the result is assigned to d. At that point in execution, when function has already returned, and execution is assigning the return value to d, the variable d has returned to scope. The variables z and b, which were 'inside function' are no longer in scope (and, they happen to no longer exist, too).
In earlier posts, this is when you were saying "when YOU'RE inside" - well, frankly, most of us do tend to think in terms of having crawled inside the computer, taken up a conductor's baton and proceed to direct the inner workings of the CPU. We tend to anthropomorphize the notions of CPU, variables, functions and the actions of a computer. It does seem to 'come alive'. However, to be clear, when you've been tempted to say "when you're inside the class" - you're really saying something along the lines of "when the point of execution is inside a member function".
Now, onto privacy and scope.
Code:
class test
{
private:
int z;
void ifunction();
public:
int j;
void pfunction();
};
int main(int, char **)
{
test t1;
t1.z = 0; // not allowed, privacy access error
t1.j = 0; // allowed, j is public
t1.ifunction(); // not allowed, privacy access error
t1.pfunction(); // allowed, pfunction is public
return 0;
}
void test::ifunction()
{
z = 0; // allowed
}
void test::pfunction()
{
ifunction(); // allowed, in scope of member function
z = 1; // also allowed
j = 2; // also allowed
}
Here we have code that won't compile, and comments illustrate why. If the 'not allowed' code were removed, the code should compile (I've not checked it, so typos could still be a problem I suppose).
When main begins execution, an instance of test is allocated on the stack, called t1. The instance of t1 is also said to be an object (or a t1 object).
Within the scope of main (that is, when the point of execution is inside main), the instance t1 is in scope. However, it is t1 in scope, not its member functions. That is, the point of execution is in main, and as such t1 is in main's scope. Any members of t1 (which are, by extension, members of the test class) are accessible only if they are declared public. As such, z is not accessible while the point of execution is in main. j is accessible, because it is public. Likewise, ifunction is not accessible because it is declared private.
Now, if the private accesses in the main function are removed such that the code could compile, execution would proceed 'into' pfunction. At the time that that point of execution is in pfunction, the members of t1 (the instance of test upon which pfunction is called) are accessible even if they are private. This is true of both pfunction and ifunction. Note, too, that the only way to call ifunction is from within the execution of another member function of t1.
Note that this is slightly different from the earlier C oriented example. C does not have privacy in it's structures, so the concept never comes to mind. However, in C++, where private and public members can be declared, the concept is relative to scope in this way: Access to private member variables and functions are only available to member functions when they are in scope - that is, when the point of execution is inside a member function.
This is a slight oversimplification. The keyword 'friend' can grant access to other classes, by name, to the private contents of a class, but that is a concept you can advance to once you have this concept better understood.
protected:
There is another level of access you can use with the keyword 'protected'. It is used just like private: is used.
In all the previous discussion, protected variables and functions are exactly like private variables and functions, but there is some difference when you inherit from a class.
Code:
class A
{
private:
int x;
protected:
int y;
public:
int z;
};
class B : public A
{
public:
void function()
{
// notes below refer to this point of execution
}
};
In this configuration, B derives from A. In A, you'll notice that y is protected. When scope is not in a member function of A (I know, there isn't one here, but pretend :) ) then y is not accessible - just as if it were private.
Now, in a member function of B (which is derived from A), y is accessible.
However, in a member function of B, x - which is private - is NOT accessible.
In other words, when you derive from a class, protected is a status that blends private and public concepts. A is a different class than B, it just so happens that B is derived from A. In A, member functions have access to private variables and functions just as before.
In B, member functions have access to A's public and protected variables and functions, but not it's private variables or functions. To all scope outside member functions of A or B, even protected variables and functions are inaccessible. They are 'as if private' to the outside world.
Within B, however, member functions of B are granted access to protected members of A. Not private, just protected.
The 'protected' status has no implication to classes NOT derived from A - it may as well be 'private' to all 'outside' scope.
I've had to handle a number of interruptions, and my time has run short so I'm not able to double check - please ask if this isn't clear and I'll come back.
-
Re: Fed up of a concept in c++
Just don't have words to say thanks to you, but wanna kiss you ummmhhhhaaaaaa!!!!!
but wanna say thanks for taking you precious time for a idiot n00b .
btw
can i have yahoo msg id?
love you bro , g
-
Re: Fed up of a concept in c++
ok friends but again stumbled upon another fach while thinking objects as instances :
http://img406.imageshack.us/img406/2064/problemsx6.jpg
@JVene: Sorryyyy Teacher I am an idiot but don't want to pester you again but still unable to understand that the rules applied on class why not applied on their instances? , thats why asking the question here! don't be rude!