• 0

Homework for Friend Functions


Question

Please help me soplve the programming problem that has been given to me as homework. I know its bad to get the source from someone else, but plezz help Im a newbie and have no idea what friend functions do: :blink:

Create 2 classes DM and DB which store the value of distance. DM store distances in meters and cm and DB in feet and inches. Write a program that can read values for the class objects and add one object DM with another object of DB.

Use a friend function to carry out the addition operation the object that stores the results may be a DM object or a DB object, depending upon the units in which the results are required. The display should be in the format of feet and inches or meters and cms depending on the object on display.

PS: I'll study what friend function means this weekend. But have to do this homework submission by tomorrow, so plezzz help. I know this may be a cakewalk for most C++ programmers, but Im still a school student.

Link to comment
https://www.neowin.net/forum/topic/190328-homework-for-friend-functions/
Share on other sites

15 answers to this question

Recommended Posts

  • 0
A friend function is a function that is not a member of a class but has access to the class's private and protected members. Friend functions are not considered class members; they are normal external functions that are given special access privileges. Friends are not in the class's scope, and they are not called using the member-selection operators (. and ?>) unless they are members of another class. A friend function is declared by the class that is granting access. The friend declaration can be placed anywhere in the class declaration. It is not affected by the access control keywords.

from MSDN.

An Example.

// friend_functions.cpp
// compile with: /EHsc
#include <iostream>

using namespace std;
class Point
{
    friend void ChangePrivate( Point & );
public:
    Point( void ) : m_i(0) {}
    void PrintPrivate( void ){cout << m_i << endl; }

private:
    int m_i;
};

void ChangePrivate ( Point &i ) { i.m_i++; }

int main()
{
   Point sPoint;
   sPoint.PrintPrivate();
   ChangePrivate(sPoint);
   sPoint.PrintPrivate();
}

  • 0

This is what I've replicated but have no idea how its gonna work or what it is doing. Just replicated the program given by you!

Plezz give me the source so that atleast I can understand how to implement the given problem after looking at the code!

#include<iostream.h>
#include<conio.h>
class db;
class dm
{
  float metre, cm;
  public: getdm()
  {
    cout << "Enter the distance in meters & centimeters";
    cout << "\nMeters: ";
    cin >> metre;
    cout <<"& Centimeters: ";
    cin >> cm;
    return 0;
  }
    friend add(dm,db);
};
class db
{
  float feet, inches;
  public: getdb()
  {
    cout << "Enter the distance in feets & inches";
    cout << "\nFeet: ";
    cin >> feet;
    cout <<"& Inches: ";
    cin >> inches;
    return 0;
  }
  friend add(dm,db);
};
add(dm meter,db feet)
{
   return 0;
}
main()
{
   clrscr();
   dm A; db B;
   A.add();
   B.add();
   getch();
}

  • 0

wot a boneidle lazy basta*d. if you arent even prepared to put a bit of work in why the hell do expect help.

i come across people like you ever year. we recruit at least one university graduate every 12 months. some of them have geniune skills, but still need the odd bit of help and got average marks. the ones that pis* me off are the ones with really high grades, but lack basis programming knowledge and have just winged the course and copied everything. they usually get laughed out of the office, but only once we sit them down with a group of developers and make them sweat a bit by throwing them into the deep end. pretty sure it sends them home and they then learn stuff.

  • 0

Thanx dangermoose and all guys, for pricking my conscience and making me work hard! I finally got the logic to the friend function and didn't go to school today. I got the program which now seems very simple to understand. But then havent yet understood the use of using friend function, since you can actually are killing the logic of encapsulation that is one of the basics of OOP.

#include<iostream.h>
#include<conio.h>
//Program to add distances using friend function
class db;
class dm
{
  float metre,cm,tot;
  public: getdm()
  {
    cout << "Enter the distance in meters & centimeters";
    cout << "\nMeters: ";
    cin >> metre;
    cout <<"& Centimeters: ";
    cin >> cm;
    tot = metre + 0.01 *(cm);
    return 0;
  }
    friend add(dm,db);
};
class db
{
  float feet, inches, total;
  public: getdb()
  {
    cout << "\n\nEnter the distance in feets & inches";
    cout << "\nFeet: ";
    cin >> feet;
    cout <<"& Inches: ";
    cin >> inches;
    total = feet + 0.0833333 *(inches);
    return 0;
  }
  friend add(dm,db);

};
add(dm C,db D)
{
   float feets,meter;
   int key;
   feets = 3.280839*C.tot;
   meter = 0.3048*D.total;
   cout << "In what units do want the addition: ";
   cout << "1.) Meters: ";
   cout << "2.) Feets: ";
   key = getch();
   if(key=='1'|| key=='2')
   {
     if(key=='1') cout << "\n\nMeters: " <<meter+C.tot;
     if(key=='2') cout << "\n\nFeets: "<<feets+D.total;
   }
   else cout <<"\n\nIncorrect Entry: PROGRAM WILL EXIT";
   return 0;
}
void main()
{
   clrscr();
   dm A; db B;
   A.getdm();
   B.getdb();
   add(A,B);
   getch();
}

Thanx all you guys.... Neowin.Net rocks!!!!

  • 0
But then havent yet understood the use of using friend function, since you can actually are killing the logic of encapsulation that is one of the basics of OOP.

Friends are useful when you implement and override global operators. In other words, instead of making add() your friend, you would make operator+() your friend and implement it like so...

dm operator+(const dm& C, const db& D)
{
    // ... similar code to the add() function...
}

It eliminates the need of having to put public setter and getter methods in your dm or db classes.

  • 0
the ones that pis* me off are the ones with really high grades, but lack basis programming knowledge and have just winged the course and copied everything.  they usually get laughed out of the office, but only once we sit them down with a group of developers and make them sweat a bit by throwing them into the deep end.  pretty sure it sends them home and they then learn stuff.

I have no clue how you would wing a 400 level csi course... lol

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Posts

    • Thank you. Will do. I read in the release notes that editor config might be at play here.
    • Actually, I think even Microsoft doesn't know how to control it
    • OpenAI is making Codex more useful in Chrome and the cloud by Pradeep Viswanathan OpenAI's Codex now has more than 5 million users, up nearly 4x from earlier this year. To further accelerate Codex's growth among developers, OpenAI today announced that it has agreed to acquire Ona, a company that builds secure cloud execution and orchestration technology for developers. Ona will enable developers to run Codex with persistent and controlled cloud infrastructure for long-running agentic workflows. Right now, most Codex execution happens locally on developers' laptops and PCs, and the agents work continuously for hours. Through Ona, OpenAI aims to make Codex agents keep working for days without being tied to a user’s local machine or an active session. This will be an important capability for enterprises that want to deploy AI agents in production while maintaining control over infrastructure, data, security boundaries, credential scope, logging, and review workflows. Like any acquisition, the deal is still subject to customary closing conditions, including regulatory approvals. Until the deal closes, OpenAI and Ona will continue to operate as separate companies. After closing, Ona’s team will join the Codex team to improve developer workflows. Alongside the Ona acquisition announcement, OpenAI today introduced a few Codex updates. Developers can now save Codex rate limit resets and use them later instead of losing them when they are not needed immediately. OpenAI is also adding a referral option where users can invite a friend to Codex and get a saved rate limit reset. OpenAI today also announced a developer mode for browser use in Chrome and the Codex in-app browser. With this mode, Codex can use the Chrome DevTools Protocol to debug web apps, inspect pages, and work more directly with browser-based development workflows. Developers can use this when they want Codex to profile JavaScript, inspect console output and network traffic, examine web page states including the DOM and applied styles, and more.
    • Camtasia 2026.1.3 by Razvan Serea TechSmith Camtasia is the complete professional solution for high-quality screen recording, video editing and sharing. Camtasia 2026 makes editing your videos easier, and faster than ever. The new editor is packed with enhanced video processing, all-new production technology, an innovative library, and stock videos and other creative assets to help you create more polished, professional videos. No video experience needed. Anyone can create informative, engaging videos. Create professional, eye-catching videos: Add special video effects - Apply Behaviors that are perfectly designed to animate your text, images, or icons. Get a crisp, polished look without being a professional video editor. Drag-and-drop your edits - What you see is what you get. Every effect and element in your video can be dropped and edited directly in the preview window. And you can edit at resolutions up to beautiful 4K, for clear video at any size. Get exceptional performance - Camtasia takes full advantage of your computer’s processor with 64-bit performance. You’ll get fast rendering times and enhanced stability—even on your most complex projects. Camtasia 2026.1.3 changelog: Feature Updates Improved keyboard navigability in tool panels. Improved screen reader accessibility of headings in Preferences. Tool panels can now be resized using a keyboard-navigable control. Updated color of folder icon in User Library tab for better visibility. Grouped media now render a composite waveform considering all audio media within that group. Added Long Path Aware to the manifest of Editor and Recorder. Performance Improvements Improved performance for editing groups on the timeline. Improved the project loading performance when timeline has lots of trec media with cursor data. Updates for IT Administrators Updated cpp-httplib from 0.38.0 to 0.43.3. Updated expat from 2.7.4 to 2.8.0. Updated freetype from 2.13.3 to 2.14.3. Updated harfbuzz from 13.0.1 to 14.2.0. Updated libpng16 from 1.6.55 to 1.6.58. Updated pango from 1.57.0 to 1.57.1. Updated girepository from 2.86.3 to 2.88.0. Updated pcre2-posix from 10.47.0 to 12.0.2. Added new harfbuzz-gpu.dll. Updated FFmpeg from 7.1.1 to 7.1.2. Updated aom from 3.11.0 to 3.13.1. Updated dav1d from 1.5.0 to 1.5.1. Updated ogg from 1.3.5 to 1.3.6. Updated SDL2 from 2.32.4 to 2.32.10. Updated zlib from 1.3.1 to 1.3.2. Updated Nalpeiron binaries to version 4.4.69.3. Bug Fixes Fixed an issue which prevented some user submitted crash reports from being sent. Fixed a potential memory leak when decoding HEVC or VP9 video. Fixed a potential crash when trying to delete a range selection on a magnetic track. Fixed a bug with the Properties Panel showing stale properties when only a caption is selected on the timeline. Fixed an issue that could prevent the Opacity and Blur properties from being changed in the Background Removal effect. Fixed an issue where larger Camtasia online projects may fail to open in Camtasia Editor. Table of contents thumbnails are no longer created for Smart Player exports with no table of contents. Fix resetting skew revert to revert just skew and not scale as well. Fixed editing in Snagit with snagX file with Unicode characters. Fixed a bug where grouped visual media could be cropped in some cases. Fixed importing SnagX files with Unicode characters. Localization fixes. Download: Camtasia 2026.1.3 | 309.0 MB (Shareware) View: Camtasia Homepage | Tutorials | Screenshot Get alerted to all of our Software updates on Twitter at @NeowinSoftware
  • Recent Achievements

    • One Month Later
      Jamswaz earned a badge
      One Month Later
    • Week One Done
      Jamswaz earned a badge
      Week One Done
    • Rookie
      Marzoid went up a rank
      Rookie
    • Community Regular
      coch went up a rank
      Community Regular
    • One Year In
      slackerzz earned a badge
      One Year In
  • Popular Contributors

    1. 1
      +primortal
      512
    2. 2
      PsYcHoKiLLa
      188
    3. 3
      +Edouard
      157
    4. 4
      Steven P.
      83
    5. 5
      ATLien_0
      75
  • Tell a friend

    Love Neowin? Tell a friend!