Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
3 views30 pages

OOPS Function Modules

The document discusses friend functions and classes in C++, explaining how they allow access to private members of other classes. It also covers static data members and functions, inline functions, and methods of passing arguments to functions, including pass by value and pass by reference. Examples illustrate the concepts, demonstrating their usage and implications in C++ programming.

Uploaded by

sellam veera
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views30 pages

OOPS Function Modules

The document discusses friend functions and classes in C++, explaining how they allow access to private members of other classes. It also covers static data members and functions, inline functions, and methods of passing arguments to functions, including pass by value and pass by reference. Examples illustrate the concepts, demonstrating their usage and implications in C++ programming.

Uploaded by

sellam veera
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 30

Friend Functions/Classes

friends allow functions/classes


access to private data of other
classes.

1
Friend Functions/Classes

Friend functions

A 'friend' function has access to


all 'private' members of the class
for which it is a 'friend'.

To declare a 'friend' function,


include its prototype within the
class, preceding it with the C++
keyword 'friend'.

2
Friend Functions/Classes
class T {
• Global function a() can access
public: private data in T
friend void a();
int m(); • m() can access private data in S
private: // ...
};
• all functions of T can access private
void a() {// can access data in X
// private data in T...}
friends should be used with caution:
class S { they by-pass C++’s data hiding
public: principle.
friend int T::m();
//...
}; It is the responsibility of the code for
which access is to be given to say
class X { who it’s friends are - i.e. who does
public: it trust!
friend class T;
//...
}; 3
Friend Functions/Classes
class Demo {
friend void Change( Demo obj );
public:
Demo(double x0=0.0, int y0=0.0):x(x0),y(y0){}
void print();
private:
double x; int y;
};

void Demo::print(){
cout << endl << "This is x " << x << endl;
cout << "This is y " << y << endl;
}

void Change( Demo obj ) {


obj.x += 100;
obj.y += 200;
cout << "This is obj.x" << obj.x << endl;
cout << "This is obj.y" << obj.y << endl;
} 4
Friend Functions/Classes
#include <iostream>
using namespace std; int getMonth(){ return month; }
void setMonth( int m ){
const int DaysInMonth[] = { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
if( m >= 1 && m <= 12 ){
enum Months { unused, January, February, March, April, May, June,
July, August, September, October, November, December }; month = m;
const char *MonthNames[]={"Unused", "January", "February", "March", "April", "May", }
"June", else{
"July", "August", "September", "October", "November", "December" }; cerr << "Invalid Month value " << m << endl;
exit(1);
class Date{ }
friend bool before( Date & d1, Date & d2 ); }

public:
int getYear(){return year;}
Date( int d=1, int m=1, int y=1970 ){ // do not use initialiser list in constructor
setMonth( m); // as here we want to reuse the checks void setYear( int y ){
setDay(d); // in the set methods // no restrictions placed on year
setYear(y); // remember month is used to verify day validity year = y;
} }
~Date(){} // no special needs for destructor
void print(){
Date( const Date & date ){ // supply an explicit copy constructor cout << day << " of " << MonthNames[month] << ", " << year << endl;
day = date.day;
month = date.month; }
year = date.year;
}
private:
int day;
int getDay(){ return day; }
void setDay( int d ){ int month;
if( d > 0 && d <= DaysInMonth[month] ){ int year;
day = d; };
}

• Continued on next slide…


else{
cerr << "Invalid Day value " << d << endl;
exit(1);
}
}
5
Friend Functions/Classes
bool before( Date & d1, Date & d2 ); // prototype

int main(){ // test the Calendar collection


Date today;
• We wanted the global
Date lecture11( 6, 8, 2008 );
today.setMonth( August );
today.setDay( 7 );
before() function to
today.setYear( 2008 );
today.print(); have access to the
lecture11.print();
if( before( lecture11 , today ) )
cout << "lecture11 was before today" << endl;
internals of the Date
Date tomorrow( 8, 8, 2008 );
if( before( tomorrow , today ) )
cout << "tomorrow was before today" << endl;
class
else
cout << "tomorrow was not before today" << endl; • Date declares it as a
return 0;
}
friend function
// return true if Date1 is before Date2
bool before( Date & d1, Date & d2 ){
if( d1.year < d2.year )

• Example output:
return true;
else if( d1.year == d2.year ){
if( d1.month < d2.month )
return true;
else if( d1.month == d2.month ){
7 of August, 2008
if( d1.day < d2.day )
return true;
6 of August, 2008
}
}
lecture11 was before today
}
return false;
tomorrow was not before today 6
Static data members
Following are the characteristics of static
member

It is initialized to zero when the first object of
its class is created. No other initialization is
permitted

Only one copy of that member is crated for
the entire class and is shared by all the object
of that class, no matter how many objects are
created

It is visible only within class, but its lifetime
is the entire program.

Static variables are used to maintain values
common to the entire class.

Eg. This can be used as a counter that records
the occcurences of all the objects

Syntax:

static datatype variblename;

Eg:

static int a;
Static Member function
• Like a static member variable we can also
have static member function. A member
function declared with static keyword is
called as static member function. static
member function has following
characteristics:
1.Static function can have access to only other
static members/functions declared in same class
2.Static member function can be called using
class name(instead of object) as
Class_name:: function_name;
• #include <iostream>
• using namespace std;
• class MyClass {
• private:
• static int staticData; // Static data member
• public:
• static void setStaticData(int value) { // Static member function
• staticData = value;
• }
• static int getStaticData() {
• return staticData;
• }
• void displayStaticData() {
• cout << "Static data value: " << staticData << endl;
• }
• };

• // Initializing the static data member outside the class definition


• int MyClass::staticData = 0;
int main() {
• MyClass::setStaticData(42); // Setting static data using static member function
MyClass obj1, obj2;
• obj1.displayStaticData(); // Displaying static data using non-static member function
• obj2.displayStaticData(); // Same as above
cout << "Static data accessed using static member function: " << MyClass::getStaticData() << endl;
return 0; 10
• }
Output:
Static data value: 42
Static data value: 42
Static data accessed using static member function: 42

Explanation:
• Initially, the static data member staticData is set to 42
using the setStaticData() static member function.
• Then, displayStaticData() is called twice using objects
obj1 and obj2, displaying the value of the static data
member, which is 42.
• Finally, the static data member is accessed directly
using the static member function getStaticData(),
which also returns 42.
11
Inline functions
add() function is

declared as inline.
#include <iostream>
• // Inline function declaration When the add()
• inline int add(int a, int b) { function is called
• return a + b; inside the main()
• } function, the
• int main() { compiler will replace
• int num1 = 5;
the function call with
• int num2 = 7;

the actual code of
// Call to inline function add()
• int sum = add(num1, num2); the add() function,
• std::cout << "Sum: " << sum << std::endl; effectively making it
• return 0; as if you had written
• } return num1 + num2;
12
Methods of Passing
• There are 3 primary methods of passing
arguments to functions:
– pass by value,
– pass by reference,
Pass By value
• When passing arguments by value, the only way to return a value back to the caller is
via the function’s return value.

– By default, arguments in C++ are passed by value.

– When arguments are passed by value, a copy of the argument is passed to the
function.

– Because a copy of the argument is passed to the function, the original argument
can not be modified by the function.
• Pass by value
When arguments are passed by value, the called function creates a new variable of the
same type as the argument and copies the argument’s value into it. As we noted, the
function cannot access the original variable in the calling program, only the copy it
created.

• Passing arguments by value is useful when the function does not need to modify the
original variable in the calling program.

• In fact, it offers insurance that the function cannot harm the original variable.
Adv. And DisAdv. Of Passing by value

Advantages Disadvantages

– Arguments passed by  Copying large structs or


value can be: classes can take a lot of time
• variables (eg. x),
to copy, and this can cause a
• literals (eg. 6),
performance penalty,
• or expressions (eg.
especially if the function is
x+1) or (eg foo()).
called many times.
– Arguments are never
changed by the function
being called, which
prevents side effects.
• Pass by reference
Passing arguments by reference uses a different mechanism. Instead of a value being
passed to the function, a reference to the original variable, in the calling program, is
passed.

• An important advantage of passing by reference is that the function can access the
actual variables in the calling program.

• This provides a mechanism for passing more than one value from the function back
to the calling program.
Pass by reference
• In pass by reference, we declare the function parameters as references
rather than normal variables:
#include <iostream>
Using namespace std ;
Void duplicate (int& a, int& b, int & c);
Int main ()
{
Int x=1,y=3,z=7;
Duplicate (x,y,z);
Cout << “x=“<<x<<“, y=“<<y<<“,z=“<<z;
Return 0;
}
Void duplicate (int& a, int& b, int & c)
{ a*=2;
b*=2;
c*=2;
}
Passing by Reference
• Reference arguments are indicated by the ampersand (&)
following the data type:
• int& a

• When the function is called, a will become a reference to the


argument.

• Since a reference to a variable is treated exactly the same as the
variable itself, then any changes made to the reference are
passed through to the argument!

Passing Arguments by Reference
Sometimes we need a function to return multiple values.
• However, functions can only have one return value.
• One way to return multiple values is using reference parameters.

•Advantages of Pass By Reference:


• It allows us to have the function change the value of the argument, which
is sometimes useful.
• Because a copy of the argument is not made, it is fast, even when used
with large structs or classes.
• We can return multiple values from a function.
Example 1
• void foo(int &y) // y is now a reference
• {
• cout << "y = " << y << endl;
• y = 6;
• cout << "y = " << y << endl;
• } // y is destroyed here

• int main()
• {
• int x = 5;
• cout << "x = " << x << endl;
• foo(x);
• cout << "x = " << x << endl;
• return 0;
• }
objects can be passed as arguments to
functions by value or by reference.
• Passing by Value: When passing
objects by value, a copy of the object
is made and passed to the function.
Any modifications made to the object
within the function do not affect the
original object.

22
• #include <iostream>
• class MyClass {
• public:
• int value;
• MyClass(int value) : value(value) {}
• };
• void modifyObject(MyClass obj) {
• obj.value += 1;
• }
• int main() {
• MyClass obj(5);
• std::cout << obj.value << std::endl; // Output: 5
• modifyObject(obj);
• std::cout << obj.value << std::endl; // Output: 5 (unchanged)
23
• return 0;
• Passing by Reference: When passing objects
by reference, a reference to the original object
is passed to the function. Any modifications
made to the object within the function will
affect the original object.

24
• #include <iostream>
• class MyClass {
• public:
• int value;
• MyClass(int value) : value(value) {}
• };
• void modifyObject(MyClass& obj) {
• obj.value += 1;
• }
• int main() {
• MyClass obj(5);
• std::cout << obj.value << std::endl; // Output: 5
• modifyObject(obj);
• std::cout << obj.value << std::endl; // Output: 6 (modified)
• return 0; } 25
• #include <iostream>
• #include <string>
• // Base class: Account
• class Account {
• protected:
• std::string accountNumber;
• double balance;
• public:
• // Constructor
• Account(const std::string& accNumber, double initBalance) :
• accountNumber(accNumber), balance(initBalance) {}

• // Virtual function for deposit


• virtual void deposit(double amount) {
• balance += amount;
• std::cout << "Deposited " << amount << " into account "
<< accountNumber << std::endl; 26
• }
• // Virtual function for withdrawal
• virtual void withdraw(double amount) {
• if (balance >= amount) {
• balance -= amount;
• std::cout << "Withdrawn " << amount << " from account
" << accountNumber << std::endl;
• } else {
• std::cout << "Insufficient funds in account " <<
accountNumber << std::endl;
• }
• }

• // Function to get balance


• double getBalance() const {
• return balance;
• }
• }; 27
• // Derived class: SavingsAccount
• class SavingsAccount : public Account {
• private:
• double interestRate;

• public:
• // Constructor
• SavingsAccount(const std::string& accNumber, double
initBalance, double rate) :
• Account(accNumber, initBalance), interestRate(rate) {}

• // Override deposit to include interest calculation


• void deposit(double amount) override {
• // Add interest before deposit
• balance *= (1 + interestRate);
• Account::deposit(amount); // Call base class method
• }
• }; 28
• // Derived class: CheckingAccount
• class CheckingAccount : public Account {
• private:
• double overdraftLimit;

• public:
• // Constructor
• CheckingAccount(const std::string& accNumber, double initBalance, double limit) :
• Account(accNumber, initBalance), overdraftLimit(limit) {}

• // Override withdrawal to allow overdraft


• void withdraw(double amount) override {
• if (balance + overdraftLimit >= amount) {
• balance -= amount;
• std::cout << "Withdrawn " << amount << " from account " << accountNumber <<
std::endl;
• } else {
• std::cout << "Exceeded overdraft limit for account " << accountNumber << std::endl;
• }
• }
• };

• int main() {
• // Creating a SavingsAccount object
• SavingsAccount savings("SAV-1234", 1000.0, 0.05);
• savings.deposit(500.0);
• 29
savings.withdraw(200.0);
• std::cout << "Savings Account Balance: " << savings.getBalance() << std::endl;
• // Creating a CheckingAccount object
• CheckingAccount checking("CHK-5678",
1500.0, 200.0);
• checking.withdraw(1800.0); // Attempting to
withdraw more than balance + overdraft limit
• std::cout << "Checking Account Balance: "
<< checking.getBalance() << std::endl;

• return 0;
• }
30

You might also like