Docsity
Docsity

Prepare for your exams
Prepare for your exams

Study with the several resources on Docsity


Earn points to download
Earn points to download

Earn points by helping other students or get them with a premium plan


Guidelines and tips
Guidelines and tips

C++ Programming: Defining and Modifying Classes with Friend Functions, Assignments of Data Structures and Algorithms

An example of defining a c++ class named box, setting its width using a setter method, and printing the width using a friend function. The code demonstrates the concept of friend functions in c++ programming, which allows access to private members of a class from outside the class.

What you will learn

  • How does the friend function access the private members of a class in this example?
  • How is a friend function declared in C++?
  • What is a friend function in C++?

Typology: Assignments

2020/2021

Uploaded on 02/13/2021

tau123
tau123 🇮🇳

8 documents

1 / 1

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
#include<iostream>
using namespace std;
class Box{
double width;
public:
friend void printWidth(Box box);
void setWidth(double wid);
};
void Box :: setWidth(double wid){
width = wid;
}
void printWidth(Box box){
box.width = box.width * 2;
cout<<"Width of box :"<<box.width<<endl;
}
int main(){
Box box;
box.setWidth(10.0);
printWidth(box);
return 0;
}

Partial preview of the text

Download C++ Programming: Defining and Modifying Classes with Friend Functions and more Assignments Data Structures and Algorithms in PDF only on Docsity!

#include using namespace std; class Box{ double width; public: friend void printWidth(Box box); void setWidth(double wid); }; void Box :: setWidth(double wid){ width = wid; } void printWidth(Box box){ box.width = box.width * 2; cout<<"Width of box :"<<box.width<<endl; } int main(){ Box box; box.setWidth(10.0); printWidth(box); return 0; }