I have a class A which has a private method called a(). I have also a class B which needs to access a() (but just B should have access to a(), thats why a() is private). I could now use a friend specifier but that would make other private methods of A (lets call them b() and c()) also available to B and I dont want that behaviour.
Is there a way to make just a() of A accessable to B?
There is a way -- if your class has a public template function:
class A {
// apparently private
void priv () { std::cout << "got you A::a()" << std::endl ; }
public:
template <class T>
void abuse() {}
};
struct Thief {};
template <>
void A::abuse<Thief>() {
this->priv();
}
int main() {
A a;
// obviously do not compile : a.priv();
// this i OK
a.abuse<Thief>();
return 0;
}
I must confess I stole this from GotW...
No there's not, but as you specify the precise class, just B could access A's private members.
You just have to take care of what method are called.
As friend relationship are not inherited, you don't have to worry about B's possible subclasses.
This could be done with some "twist".
Just factor out method a() from A class into a parent class that has B as a friend class, then let A inherit it. this will leave a() as being a method in A, but the only private method accessible by its parent's friend B.
here is a very simple code to clarify what I've said:
class parent
{
friend class B;
private:
void a() {}
};
class A:public parent
{
private:
void b() {}
void c() {}
};
class B
{
A* m_a;
public :
B()
{
m_a = new A();
m_a->a(); // OK
m_a->b(); // error C2248: 'A::b' : cannot access private member declared in class 'A'
}
};
hope it helps !
Yes, I have an easy way. Let B have a pointer of A::a(), like this:
typedef boost::function<void ()> functype;
class A {
private:
void a();
};
class B {
public:
void setfp(functype f) {m_f = f;}
void foo() {
// do some stuff
m_f();
}
private:
functype m_f;
};
A a;
B b;
b.setfp(boost::bind(&A::a, &a));
b.foo();
Related
I wonder what is the proper way to assign/override a method from that of another class. For example, here below classes A and B are not and should not be subclassed, but method "A.foo" is a prototype and should be assinged/set in the initialization of B. That is, "A.foo = B.bar_b" (or C or D etc). (The overall idea is to register a send method of servers (B) with a client (A).)
class A {
public:
virtual void foo(arg argA) {
// empty
};
};
class B {
public:
B(A a) {
a.foo = &B::bar_b;
}
void bar_b(arg argA) {
// do stuff B
};
};
A a;
B b(a);
a.foo(arg) // calls bar_b
It doesn't work that way. There are two ways to answer your question. The first is to use proper overriding:
class A {
public:
virtual void foo() {
// empty
};
};
class B : public A {
public:
void foo() override {
// do stuff B
};
};
B b;
A& b_ref = b;
b_ref.foo(); // calls B::foo
The other way is trying to interpret what you actually want to do. Perhaps you want to swap some implementation at runtime to select what A::foo is actually doing.
You need a B to call a method of the class B. Also B(A a) passes the A by value and the assignment in the constructor wont have any effect on the A you pass. Though, most importantly you cannot dynamically assign member functions. However, you can assign to member variables:
#include <functional>
struct A {
public:
void foo() {
do_foo();
};
std::function<void()> do_foo;
};
class B {
public:
B() = default;
B(A& a) {
a.do_foo = [](){B b; b.bar_b(); };
}
void bar_b() {};
};
I have the following design:
- one class A that has a protected member of class M.
- one class B that inherits from A and has a pointer to an object of class C
- one class C that needs to have access to the member of the class A
class A {
public:
A() : _member(0) {}
~A() { delete _member }
protected:
M _member;
}
class B : public A {
public:
B(){}
~B(){}
protected:
C* c;
}
class C {
// C needs to have access to _member
}
What design should be more appropriate to solve this issue ?
In pure OO terms, allowing a class to directly access the internal fields of another class is bad practice.
That said, C++ is not a pure OO language, and does allow for this (among other important deviations from OO).
To allow access to a private member to another class, you must designate that class to be a friend. Friendship, however is not passed to derived classes, therefore you must upcast the class to the type you need.
This is your simplest solution:
class A {
public:
A() : _member(0) {}
~A() { delete _member }
protected:
friend class C;
M _member;
}
class B : public A {
public:
B(){ c = new C(this); } // this call will cast the B* to an A* (important)
~B(){ delete c;}
protected:
C* c;
}
class C {
public:
C(A* a) { _a->_member = new M(); } //Now C can directly access _member in A
}
In such a way, any object derived from A can be turned back into an A* and used to access _member.
However, as previously stated, any classes derived from C will not gain access to _member, as friendship is not inherited, so a more comprehensive solution is required:
class M {
public:
void Foo() { printf("Foo called\n"); }
};
class A {
M* m;
friend class C;
public:
A():m(0) { ; }
};
class B :public A {
int id;
public:
B() { id = 0; }
};
class C {
public:
C() { _a = 0; }
C(A* a) { _a = a; }
protected:
M* getM() { return _a->m; }
void setM(M* m_) { _a->m = m_; }
private:
A* _a;
};
class D : public C {
public:
D(B* b): C(b) {
}
void Foo() {
setM(new M());
getM()->Foo();
delete getM();
setM(nullptr);
}
};
int main()
{
B* b = new B();
D d(b);
d.Foo();
delete b;
getchar();
return 0;
}
In this way, no classes derived from A provide direct access to _member, and no classes derived from C have direct access, but the member variable can still be accessed via C's protected API. This also prevents other external objects accessing it.
Make C a friend of A:
class A {
friend class C;
/*and so on*/
Then C can see all member variables and functions in A, even if they are private.
I have the following structure, and I would like to call foo from D. How is it possible? I got the error message, that I commented at the line below.
class A
{
protected:
class B
{
public:
B(x)
{
//...
}
protected:
virtual void foo()
{
//...
}
};
};
class C : public A
{
protected:
class D : public A::B
{
public:
D(x) : B(x)
{
//empty
}
};
void bar()
{
D var = D(x);
var.foo(); //cant access protected member in class A::B
}
};
foo() is protected member function of B, means that foo() is only allowed to be called from its subclass( child class).
bar() is member function of C, and C is inheritance from A. So ,C is not subclass of B.
If you put bar in D, that's OK.As code below:
class A
{
protected:
class B
{
public:
B(int x)
{
//...
}
protected:
virtual void foo()
{
//...
}
};
};
class C : public A
{
protected:
class D : public A::B
{
public:
D(int x) : B(x)
{
//empty
}
// Here is OK, while D is subclass of B
void bar()
{
int x;
D var = D(x);
var.foo(); //cant access protected member in class A::B
}
};
// void bar()
// {
// int x;
// D var = D(x);
// var.foo(); //cant access protected member in class A::B
// }
};
int main(){
return 0;
}
Try a friend class. You can make D a friend of B, and that should allow D to call foo().
Actually you are trying to access from the class C a protected method of the class D ==> You can't access protected methods from the external of a class.
One solution could be to declare C as a friend class of D so C can access protected methods:
// ...
class D : public A::B
{
public:
D(x) : B(x)
{
//empty
}
// Declare C as friend of D
friend class C;
};
// ...
Adding the friendship declaration your code will compile and will work as expected.
You might want foo() to be public in D even though it is protected in A::B
If so you can add the following line after the public: line in the definition of D
using A::B::foo;
Thanks for the answer. Making the foo function public is really a solution, but I really want foo only available from inherited class. The friend modifier is a thing, what many people hate, because it gives you access for things, thats you should not access.
But also you were right guys, I should access B::foo from D (from constructor is not an option is my case). I could create a function, which calls the original foo, so my solution is:
class A
{
protected:
class B
{
public:
B(x)
{
//...
}
protected:
virtual void foo()
{
//...
}
};
};
class C : public A
{
protected:
class D : public A::B
{
public:
D(x) : B(x)
{
//empty
}
Dfoo()
{
B::foo();
}
};
void bar()
{
D var = D(x);
var.Dfoo();
}
};
The solution was easy, but I did not know that a function (what is not static) can be called like this :)
Ok I'm totally frazzled on this. Code is begin to swim around the screen...must sleep.
So! Ok, troubled by nested classes and friends.
here is the pseudo-code
class A{
public:
//constructor
// member functions
private:
class B{
//private
int a();
};
class C{
//private
int b();
};
};
So once an object of type A has been created, I would like it to access a() and b(). I know that I have to use a friend function for this. So where should I put friend class A. Is that the right expression?.
If you would like to access a() and b() from within class A you need to place the friend declaration inside of class B and class C. However, a() and b() are not members of class A so you cannot access them in the way you are thinking. Instead you also need to add forwarding functions to A.
class A
{
public:
//constructor
// member functions
private:
class B
{
//private
int a();
friend A; // <-- make A a friend
};
class C
{
//private
int b();
friend A; // <-- make A a friend
};
public:
// forwarding function for a
int a()
{
return bdata_.a();
}
// forwarding function for b
int b()
{
return cdata_.b();
}
private:
B bdata_;
C cdata_;
};
Suppose an object of class B is a member of class A.
class B{
//Definitions
}
class A{
public:
A();
B b_child;
int some_function();
}
One of the functions defined inside B needs to call a (public) function from its owner (parent?) A. Is there an immediate way to do this?
The only way I've managed to do this so far was to implement it outside the classes' definitions:
A a_obj;
a_obj.b_child.setowner(&aobj);
which tells b_child who is its owner. I don't like this. I'd rather use some builtin method for b_child to access its parent (if possible). If that's not possible, I'd rather pass the owner's address directly in the constructor for B, but I don't know how to reference A's address inside its definition.
There is no builtin method to get the 'owner' of a variable, whatever that means. Your approach of setting the owner is correct. Furthermore, doing so in the construction of B is also a correct decision. Sample code:
class B
{
public:
explicit B( A* owner ) : _owner( owner ) {}
...
private:
A* _owner;
};
class A
{
public:
A() : _child( this ) {}
...
private:
B _child;
};
Note some compilers may give you a warning for using this in that context, but its ok for the current example. Just make sure you don't call any A member functions from within B constructor, since the pointer you get still points to an unconstructed object at that stage.
I'd rather use some builtin method for b_child to access its parent (if possible).
No, it's not.
but I don't know how to reference A's address inside its definition.
You can use this pointer.
A() : b_child(this) { }
You should use this pointer to refer to the object within itself
class B{
//Definitions
}
class A{
private:
B b_child;
public:
A()
{
b_child.set_owner(this);
}
}
You should define B like the following:
template <class T, int N>
class B
{
public:
int example_func() { return static_cast<T&>(*this).some_function(); }
};
And then make B<A> a subclass of A (so it can call A directly).
class A : protected B<A,0>, protected B<A,1>
{
A();
int some_function() { return 42; }
};
This is called the curiously recurring template pattern.
If you don't want B to be a template class, and you're only going to use B with A, then the following is fine:
template <int N>
class B
{
public:
int example_func() { return static_cast<A&>(*this).some_function(); }
};
class A : protected B<0>, protected B<1>
{
A();
int some_function() { return 42; }
};
Alternatively, if you want to use B with not just A, but don't want to make B a template class (say, if you want a collection of pointers to B), you can do the following:
template <int N>
class B
{
public:
int example_func() { return some_function(); }
virtual int some_function() = 0;
};
class A : protected B<0>, protected B<1>
{
A();
int some_function() { return 42; }
};
This will resolve the some_function() call at run-time, and require a virtual pointer to be stored in your class.