Friendship examples

[1] Function with access to class C members

.hpp

#include <iostream>

class C{
    int m;
    friend void func(C obj);
public:
    C(int m);
};
void func(C obj);

.cpp

#include "name.hpp"

C::C(int m){
    C::m = m;
}
void func(C obj){
    std::cout << obj.m << std::endl;
}

[2] Member of class B with access to class C members

.hpp

#include <iostream>

class C;

class B{
public:
    void method(C obj);
};

class C{
    int m;
    friend void B::method(C obj);
public:
    C(int m);
};

.cpp

#include "name.hpp"

C::C(int m){
    C::m = m;
}
void B::method(C obj){
    std::cout << obj.m << std::endl;
}

[3] All members of class B with access to class C members

.hpp

#include <iostream>

class C;

class B{
public:
    void method1(C obj);
    void method2(C obj);
};

class C{
    int m;
    friend class B;
public:
    C(int m);
};

.cpp

#include "name.hpp"

C::C(int m){
    C::m = m;
}
void B::method1(C obj){
    std::cout << obj.m << std::endl;
}
void B::method2(C obj){
    std::cout << obj.m << std::endl;
}
Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s