Functions and Objects

Friend Class in C++

A friend class can access all members (private or protected) of a class in which it is declared a friend.


Syntax
class originalClass {
     friend class friendClass; //friendClass is a friend of originalClass

    private:
        dataType privateMember;
}

class friendClass {
    public:
        returnType someFunction(originalClass c){
            c.privateMember = value; //private member of originalClass can be accessed
        }
}

Notes

A friend class can access private and protected members of an object created from the originalClass, or an object of type originalClass passed in as a function parameter.


Example
//point on an x-y plane
class Point {
        friend class Triangle;
    private:
        int x, y;
}

//triangle created from point plotted on x-y plane, using x, y, and the origin
class Triangle {
    public:
        int Base(Point p){
            return p.x; //direct access to x, which is private member of p object
        }
        int Height(Point p){
            return p.y;
        }
        double Area(Point p){
            return p.x * p.y / 2;
        }
}

< Friend Function   |   Destructor >

© 2019 SyntaxDB. All Rights Reserved.