element14 Community
element14 Community
    Register Log In
  • Site
  • Search
  • Log In Register
  • About Us
  • Community Hub
    Community Hub
    • What's New on element14
    • Feedback and Support
    • Benefits of Membership
    • Personal Blogs
    • Members Area
    • Achievement Levels
  • Learn
    Learn
    • Ask an Expert
    • eBooks
    • element14 presents
    • Learning Center
    • Tech Spotlight
    • STEM Academy
    • Webinars, Training and Events
    • Learning Groups
  • Technologies
    Technologies
    • 3D Printing
    • FPGA
    • Industrial Automation
    • Internet of Things
    • Power & Energy
    • Sensors
    • Technology Groups
  • Challenges & Projects
    Challenges & Projects
    • Design Challenges
    • element14 presents Projects
    • Project14
    • Arduino Projects
    • Raspberry Pi Projects
    • Project Groups
  • Products
    Products
    • Arduino
    • Avnet Boards Community
    • Dev Tools
    • Manufacturers
    • Multicomp Pro
    • Product Groups
    • Raspberry Pi
    • RoadTests & Reviews
  • Store
    Store
    • Visit Your Store
    • Choose another store...
      • Europe
      •  Austria (German)
      •  Belgium (Dutch, French)
      •  Bulgaria (Bulgarian)
      •  Czech Republic (Czech)
      •  Denmark (Danish)
      •  Estonia (Estonian)
      •  Finland (Finnish)
      •  France (French)
      •  Germany (German)
      •  Hungary (Hungarian)
      •  Ireland
      •  Israel
      •  Italy (Italian)
      •  Latvia (Latvian)
      •  
      •  Lithuania (Lithuanian)
      •  Netherlands (Dutch)
      •  Norway (Norwegian)
      •  Poland (Polish)
      •  Portugal (Portuguese)
      •  Romania (Romanian)
      •  Russia (Russian)
      •  Slovakia (Slovak)
      •  Slovenia (Slovenian)
      •  Spain (Spanish)
      •  Sweden (Swedish)
      •  Switzerland(German, French)
      •  Turkey (Turkish)
      •  United Kingdom
      • Asia Pacific
      •  Australia
      •  China
      •  Hong Kong
      •  India
      •  Korea (Korean)
      •  Malaysia
      •  New Zealand
      •  Philippines
      •  Singapore
      •  Taiwan
      •  Thailand (Thai)
      • Americas
      •  Brazil (Portuguese)
      •  Canada
      •  Mexico (Spanish)
      •  United States
      Can't find the country/region you're looking for? Visit our export site or find a local distributor.
  • Translate
  • Profile
  • Settings
Code Exchange
  • Technologies
  • More
Code Exchange
Blog C++ friend functions
  • Blog
  • Forum
  • Documents
  • Events
  • Polls
  • Files
  • Members
  • Mentions
  • Sub-Groups
  • Tags
  • More
  • Cancel
  • New
Join Code Exchange to participate - click to join for free!
  • Share
  • More
  • Cancel
Group Actions
  • Group RSS
  • More
  • Cancel
Engagement
  • Author Author: Jan Cumps
  • Date Created: 18 May 2025 9:47 AM Date Created
  • Views 448 views
  • Likes 6 likes
  • Comments 4 comments
  • code_exchange
  • Modern C++
  • embedded
  • c++
Related
Recommended

C++ friend functions

Jan Cumps
Jan Cumps
18 May 2025

For an embedded design, I made a featherweight class. A C++ construct that used no more data or code size than a traditional C design.

class command {
public:
    inline command(uint32_t steps, bool reverse) : cmd_(steps << 1 | (reverse ? 0 : 1)) {
        assert(steps <= (UINT32_MAX >> 1)); 
    }
    inline operator uint32_t() const { return cmd_; }
    friend uint32_t steps(const command &cmd);
    friend bool reverse(const command &cmd);
private:
    uint32_t cmd_;
};

It's an interesting little structure. In memory, any object just takes the exact same size as an uint32_t.
The code size (if this class is used somewhere) is tiny too. Only the code of the constructor will be inline inserted into your code base. Any other code of that class is optimised away. Using this class is exactly the same as using an unsigned int, and using a shift then set its last bit.

This is a class that can hold a number of steps, and a direction bit, in a 32 bit variable. Bit 0 (LSB) is the direction, all the other bits are the number of seps a stepper motor would take

This info is passed to a stepper motor API. My library - after creating the class object - does not need to know what part of the uint32_t is the number of steps, and what's the direction.
But you, as a user, may be interested in that info. Maybe to check the requested steps and make decisions on that. Maybe to know what direction the motor is turning.

Friend Functions

I could extend the class definition, and provide the logic to extract dir and steps from that single uint32_t. But most firmware wouldn't need it. Nonetheless, I added that possibility to the class definition, as a set of friend clauses. friend functions have access to the object's protected and private sections.

With the current state of compiler optimisation, I could have used member functions in the command class. If they aren't used in your project, the optimiser will happily cull them. So don't read this post as an optimisation exercise. I used the friend structure here s a lazy mechanism: I'll implement it if I need it

My commands class is listed at the start of this post. You can see that it accepts two functions as friend:

class command {
public:
    // ...
    friend uint32_t steps(const command &cmd);
    friend bool reverse(const command &cmd);
    // ....
};

I can now declare these functions outside the class, and use them in my firmware. This is an implementation of the functions. Again very cheap. It will result in assembly that just returns the data member.

inline uint32_t steps(const command &cmd) { return cmd.cmd_ >> 1; }
inline bool reverse(const command &cmd) { return !(cmd.cmd_ & 1); }

And here I use them in firmware:

for (auto &c: cmds) {
    printf("steps %d, reverse %d\n", steps(c), reverse(c));
}

You may not need friend functions in your code base. But it's one of the tools that you can use to make reusable APIs.
Are there downsides? Yes: they weaken class encapsulation. Under a known contract though.

Thank you for reading.

  • Sign in to reply
  • DAB
    DAB 3 months ago

    New declaration for me.

    • Cancel
    • Vote Up 0 Vote Down
    • Sign in to reply
    • More
    • Cancel
  • Jan Cumps
    Jan Cumps 3 months ago in reply to Jan Cumps

    That optimiser is awesome Slight smile. Here it is in action with an array of command objects

    image

    It also shows that an stl array is a very cheap object. Perfect container for use in an embedded program.

    • Cancel
    • Vote Up 0 Vote Down
    • Sign in to reply
    • More
    • Cancel
  • Jan Cumps
    Jan Cumps 3 months ago

    For the compiler (with optimisation on) it doesn't matter if you use a friend or an inline non-virtual class member

    image

    Isn't it amazing how much abstraction you can get for free? The compiler translates both examples as if you just wrote this:

    int main() {
        return 200;
    }

    • Cancel
    • Vote Up 0 Vote Down
    • Sign in to reply
    • More
    • Cancel
  • shabaz
    shabaz 3 months ago

    Very interesting! I've not used the friend declaration before (I don't think it was very prevalent when I coding in C++), so it's new to me. And looks a lot cleaner than having to resort to 'setter' and 'getter' type methods!

    • Cancel
    • Vote Up 0 Vote Down
    • Sign in to reply
    • More
    • Cancel
element14 Community

element14 is the first online community specifically for engineers. Connect with your peers and get expert answers to your questions.

  • Members
  • Learn
  • Technologies
  • Challenges & Projects
  • Products
  • Store
  • About Us
  • Feedback & Support
  • FAQs
  • Terms of Use
  • Privacy Policy
  • Legal and Copyright Notices
  • Sitemap
  • Cookies

An Avnet Company © 2025 Premier Farnell Limited. All Rights Reserved.

Premier Farnell Ltd, registered in England and Wales (no 00876412), registered office: Farnell House, Forge Lane, Leeds LS12 2NE.

ICP 备案号 10220084.

Follow element14

  • X
  • Facebook
  • linkedin
  • YouTube