Why this code is working ? I mean the member is private - c++

why this code is working? I mean the value is a private variable, why function assign() can access it directly?
class A {
private:
int value;
public:
A() :value(0){ }
void assign(A x)
{
value = x.value;
}
};
int main()
{
A a;
A b;
a.assign(b);
return 0;
}

The private keyword means that no code outside the class can access the class.
Methods of the same class can access it, sure, because if they couldn't nobody could access private variables and they'd be useless.
If you worry about the access from the method called for A to the private member of B, don't worry.
The idea of private and public is making the implementation details of the class a thing nobody knows (and needs to know), but the class itself.
The class A "knows" how A itself is implemented, and so is "allowed" to use it's internals - privates, even if they're not of the called object.

Member functions (e.g., A::assign(A)) can access private members of their respective class, in addition to protected members of inherited classes.

int value is private, but void assign(A x) is public. In main function (outside class A) you can access only to public methods. Inside class A (for example in assign method) you can access to public, private and protected members
For example:
You can't write something like this:
A obj;
obj.value;
because value is private.
But you can access it using other methods: for example you can define set(int val) method
class A {
private:
int value;
public:
A() :value(0){ }
void set(int val)
{
value = val;
}
void assign(A x)
{
value = x.value;
}
};
int main()
{
A obj;
obj.set(10);
}

Related

friend function pointer parameter in constructor

i'm trying to create a costructor in the form
class A {
public:
A(void (*initializer)(A&))
{
initializer(*this);
}
};
where initializer take a reference to the instance he's passed and can make custom operation on variable it is initializing. Is there a way to make such a function friend so it can access to private variables too?
Here is a simple way:
class Impl
{
public:
int x;
int y;
};
class A
{
public:
A(void (*initializer)(Impl&))
{
initializer(_impl);
}
private:
Impl _impl;
};
This hides _impl from everyone except initializer. And since nobody other than initializer can access _impl at all, the members of of class Impl can be public, making it easy for initializer to mutate them.
Other than listing all the functions you want to pass pointers to as friends separately, no. An alternative may be to separate the data into a base class with public members you inherit privately from:
struct AData
{
int m_privateInt;
...
};
class A : private AData {
public:
A(void (*initializer)(AData&))
{
initializer(*this);
}
};
You may need to also pass a reference to A, if you want to access its member functions in initializer.

Why won't this code, implementing PassKey pattern, compile?

Here is the code, c++11 :
#include<stdio.h>
#include<iostream>
template<typename T>
class Passkey
{
friend T;
Passkey() {}
Passkey(const Passkey&) {}
Passkey& operator=(const Passkey&) = delete;
};
class Access;
class MyClass
{
public:
MyClass() {}
private:
void func(Passkey<Access>) { std::cout<<"here" << std::endl;}
};
class Access
{
public:
void tryme(MyClass& c) { c.func(Passkey<Access>());}
};
int main ()
{
MyClass c;
Access a;
a.tryme(c);
return 0;
}
Compiler is giving the following errors:
prog.cpp: In member function 'void Access::tryme(MyClass&)':
prog.cpp:21:12: error: 'void MyClass::func(Passkey<Access>)' is private
void func(Passkey<Access>) { std::cout<<"here" << std::endl;}
^
prog.cpp:27:56: error: within this context
void tryme(MyClass& c) { c.func(Passkey<Access>());}
As pewt said, MyClass::func() must be public in order for Access::tryme() to be able to access it. In the example you linked in the comments, Citizen::getSocialSecurityNumber() is actually public. And that is fine, because the access is limited in a different way.
Your MyClass::func() takes a Passkey<Access> parameter – and no one is actually allowed to construct such an object apart from the Access class itself. All of Passkey's functions are private. By construction, Access is the only friend of Passkey<Access>, so only Access can construct the “key” required to call func(). So func() behaves as if it were private, without actually being private itself.
func() is a private method for MyClass. Access can't call func unless it is made a friend of MyClass.
Making PassKey a friend of Access does not (as far as I know...) allow use of MyClass's private methods.
Via https://en.wikipedia.org/wiki/C%2B%2B_classes#Member_functions
The private members are not accessible outside the class; they can be accessed only through methods of the class.
And When should you use 'friend' in C++?

Read private variables class members

I'm new to c++ and I need to read from private class members of a class in a method that's in a different class, for example:
class a{
private:
int x;
}
class b{
void foo();
}
void b::foo(){
//here I want to read from x that's in a
}
Do I have to set up a function in class a like int readx(){return x);) or a readclass(){return *this);}? Is there another way?
The private section of a class has the objective of 'hiding' the way you handle the data, providing a streamlined way of accesing said data with public methods.
The advantage of using a public method to change the value of private members is that you can, for example, allow values only between 0 and 10 for 'x'.
In your case, you should think about what does 'x' represent in your first class, and if it makes sense for the second class to access it directly and without any control or special consideration. If this is the case, it should probably be a public value. In the other case, you will need to make a public method to read it, like your readx example.
If only 'b' has the privilege to access 'x' directly, you can also define a friend function, like someone already said.
Note that returnig a pointer to the instance wouldn't allow access to private members of the class.
You could use friend class or function, but it is a bad idea to use private members of methods (tests are only reasonable excuse for that). Better to use public methods for that or redesign your code if you couldn't avoid usage of private members.
You can implement a friend function that can access x in foo.
Reference
If there is no accessor to this data member in class a then you should declare the member function of class b as a friend function of class a.
For example
#include <iostream>
class B
{
public:
void foo() const;
};
class A
{
public:
A( int x ) : x( x ){}
private:
friend void B::foo() const;
int x;
};
void B::foo() const
{
A a { 10 };
std::cout << a.x << std::endl;
}
int main()
{
B().foo();
return 0;
}
Declaring a friend function or class would grant read and write access to a's x to that function or class, a
class a {
public:
const int& readx() const { return x; }
private:
int x
};
or, if you like that semantics better
class a {
public:
const int& x() const { return x_; }
private:
int x_;
};
grants read access only, but to every client.

Why do C++ classes not have access specifiers like classes in Java have?

I'm new to C++, and I'm familiar with Java. The first thing I was wondering about when I started looking at C++ code is that classes themselves (not the members) don't have access specifiers such private, protected and public. Exemples here and here.
public class A { // This line.
private class B { } // Not this line.
}
Why is that so?
There's no access modifier at the level of classes, since the language has no concept of package. But there is at the level of data members, member functions and inheritence:
class Foo {};
class Bar : public Foo {
public:
void bar() const {}
private:
int bar_(float) {}
int a, b, c;
};
The closest you can get is declaring nested classes inside a class:
class Foo {
struct Bar0 {
void bar0() const {}
};
struct Bar1 {
Bar0 b0;
Bar1() { b0.bar0();}
};
};
There's no need for class-level access specifier. If you want a private class, you can define it in an implementation file or an anonymous namespace. This sort of restriction is done at file-level for C++ (i.e. how you organize your headers, preprocessor directives).
Before edit:
They do, but they're not per-method. Also, classes have a default private specifier, so, unless otherwise noted, they are private.
class A
{
void foo(); //private
};
class B
{
void foo(); //private
public:
void foo1(); //public
void foo2(); //public
protected:
void foo3(); //protected
private:
void foo4(); //private
};
Note 1 C++ also has struct, which is identical to a class except the default access level is public.
Note 2 There is no package-scope in C++. In Java, protected gives access to the whole package, in C++ it just gives access to deriving classes.
Note 3 The friend keyword can be used to bypass restrictions, look it up.
C++ uses a slightly different syntax where access modifiers are specified for groups of declarations instead of individually:
class Test {
class MyPrivateClass {
// ...
};
void privateByDefault();
public:
void myPublicFunction();
void anotherPublicFunction();
private:
void myPrivateFunction();
public:
class MyPublicClass {
// ...
};
void morePublicFunctions();
protected:
// ...
};
Test::MyPrivateClass is inaccessible outside of Test, while Test::MyPublicClass can be used anywhere.
From your source: http://www.cplusplus.com/doc/tutorial/classes
private members of a class are accessible only from within other
members of the same class or from their friends. protected members are
accessible from members of their same class and from their friends,
but also from members of their derived classes. Finally, public
members are accessible from anywhere where the object is visible.

Need Help in Inheritance

I have read this question,
I still have doubts in my concepts of inheritance.I have tried to solve a homework assignment but I think that I still don't get the access levels. I have following questions in my mind,
Is protected and public
access specifier same? (I don't find a
difference)
My assignment is attached below,please help me out if it is incorrect.
The difference is that protected members are only visible/accessible to child classes.
class A {
public:
int a; // anything can access this member.
private:
int b; // only A can access this member.
protected:
int c; // A and every other class that inherits this member can access it.
};
No, they're not the same.
public means that any other class can access the member.
private means it's only accessible by it's own class
protected means it's accessible by the own class, and all classes derivated from the class
Example:
class 1 {
public void do1() { }
private void do3() { }
protected void do2 { }
1()
{
public void do1() { } // ok
private void do2() { } // ok
protected void do3 { } // ok
}
}
class 2 {
2()
{
1.do1() { } // ok
1.do2() { } // ERROR
1.do3 { } // ERROR
}
}
class 3 inherits class 1 {
3()
{
do1() { } // ok
do2() { } // ERROR
do3 { } // ok = this class can access the the protected member of it's base class
}
}
You seem to have forgotten the simplest and the most important aspect: Accessibility of members from an unrelated class / in a freestanding (non-member) function. Public members can be accessed from outside the class and the class hierarchy, private and protected ones cannot.
If you mean public vs protected inheritance, well, the answer is there on your charts.
Protected members of a Base class can only be accessed by the Base class and class derived from base class.
**Private Members** can be only accesed by its own class and cannot be accesed by the derived class.
**Public members** can be accessed by any class including the derived class.
Please check this question