0% found this document useful (0 votes)
67 views20 pages

Friend Function and Constructor and Destructor

The document discusses friend functions in C++, which allow access to private data of classes and can be declared as friend functions of other classes. It also covers constructors and destructors, explaining their roles in object initialization and destruction, including default, parameterized, and copy constructors. Additionally, it provides examples and practice exercises related to these concepts.

Uploaded by

Pratit Raj Giri
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
67 views20 pages

Friend Function and Constructor and Destructor

The document discusses friend functions in C++, which allow access to private data of classes and can be declared as friend functions of other classes. It also covers constructors and destructors, explaining their roles in object initialization and destruction, including default, parameterized, and copy constructors. Additionally, it provides examples and practice exercises related to these concepts.

Uploaded by

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

Friend Functions, Constructors

and Destructors
Friend Functions
• C++ allows a functions to be friendly, allowing the function to
have access to the private data of classes
• These functions might not be member of any of those classes

class myClass
{
……..
public:
……..
friend void function_name(); //friend function declaration
}
Example
class sample
{
int a;
int b;
public:
void setvalue(){a=10;b=20;}
friend float mean(sample s);
};
float mean(sample s)
{
return float(s.a+s.b)/2.0;
}
int main()
{
sample x;
x.setvalue();
cout<<“Mean value = “<<mean(x)<<“\n”;
return 0;

}
Friend Functions contd..
• Member functions of one class can be friend functions of another class
class X
{
……..
int fun1():
……..
};
class Y
{
………
friend int X::fun1(); //fun1() of X is friend of Y
……….
};

• All the member functions of a class can be declared as friend functions of


another class ---> friend class
class Z
{
……..
friend class X; //all member functions of X are friends to Z
……..
};
Example
class ABC; //forward declaration int main()
class XYZ {
{ ABC abc;
int x; int a,b;
public: cout<<“Enter value for class ABC: “;
void setvalue(int i){x=i;} cin>>a;
friend void max(XYZ,ABC); abc.setvalue(a);
}; XYZ xyz;
class ABC cout<<“\nEnter value for class XYZ: “;
{ cin>>b;
int a; xyz.setvalue(b);
public: max(xyz,abc);
void setvalue(int i){a=i;} return 0;
friend void max(XYZ,ABC); }
};
void max(XYZ m, ABC n) //Definition of friend
{
if(m.x>=n.a)
cout<<“ \nXYZ has max value = ”<<m.x;
else
cout<<“\nABC has max value = ”<<n.a;
}
• Friend function can be called by reference as well. Try it
yourself.
Lets Practice
• WAP to add multiply and divide private
member variables of two different class using
friend function.
Lets Practice
• WAP to take input from user (name , age,
contact number) and display the data using
input and display function any one being a
friend to the class.
Constructors
Think about this code….
class student
{
int roll_number;
float marks;
public:
void insertdata(int a,float b);
void displaydata(void);
};
void student::insertdata(int a, float b)
{
roll_number = a;
marks = b;
}
void student::displaydata(void);
{
cout<<"Roll Number: "<<roll_number<<"\n";
cout<<"Marks: "<<marks<<"\n\n";
}
int main()
{
int student_roll;
float student_marks;
student x;
cout<<"Enter Roll Number:\n";
cin>>student_roll;
cout<<"Enter Marks:\n";
cin>>student_marks;
cout<<“Student info:\n";
x.insertdata(student_roll, student_marks);
x.displaydata();
return 0;
}
• How are initial values
By invoking a
assigned in the given code ? member function
insertdata()
• Function call statements are
used with the appropriate
objects that have already
been created
• These can’t be used to
initialize the member
variables at the time of
creation of their objects
• The essence of C++ is that we should be able to initialize a
class type variable (object) when it is declared, like
initialization of an ordinary variable int m = 20;
• Also, when a variable of built-in type goes out of scope, the
compiler automatically destroys the variable. Think about the
objects we have created so far. Does this happen in these
objects ?
• C++ provides a special member function called the
constructor which enables an object to initialize itself when it
is created, known as automatic initialization of objects
• C++ also provides another member function called destructor
which destroys the objects when they are no longer required
Constructors
• A constructor is a special member function whose task is to initialize the objects of
its class. Constructor has the same name as that of class
• A constructor is a member function that is invoked automatically when an object is
declared. A constructor function must have the same name as the class itself, and
it is declared without return type. (Schaums)
class ratio
{ void ratio::print(void)
public: {
cout << num << '/' << den;
ratio(void);
}
void print(void); int main()
private: {
int num,den; ratio x;
}; cout << "x = ";
ratio::ratio(void) x.print();
{ }
num = 1;
den = 2;
} Default constructor ?
Characteristics of Constructors
• Should be declared in the public section
• Invoked automatically when objects are
created
• No return types, not even void
• Can’t be inherited, though a derived class can
call the base class constructor
• Can have default arguments
• Can’t be virtual
Parameterized Constructor
• The constructors that can take arguments are called parameterized constructors
• In this case we must pass the initial values as arguments to the constructor
function when an object is declared. Two ways:

ratio x = ratio(-1,3) By calling the constructor explicitly


ratio x(-1,3) By calling the constructor implicitly

class ratio void ratio::print()


{ public: {
ratio(int n,int d); cout << num << '/' << den;
void print(); }
private: int main()
int num,den; { ratio x(-1,3), y(22,7);
}; cout << "x = ";
ratio::ratio(int n,int d) x.print();
{ cout << " and y = ";
num = n; y.print();
den = d; }
}
Copy Constructors
• Takes a reference to an object of the same class as itself as an
argument
class ratio int main()
{ {
private: ratio x(100,360);
int num,den; ratio y(x);
public: cout << "x = ";
ratio(int n=0,int d=1):num(n),den(d){ } x.print();
//ratio(int n=0,int d=1){num=n;den=d;} cout << ",y = ";
ratio(const ratio& r) : num(r.num), den(r.den) { } y.print();
//ratio(const ratio& r) {num=r.num; den=r.den; } }
void print() { cout << num << '/' << den; }
};
Dynamic Constructors
• Allocation of memory to objects at the time of their
construction
• Memory is allocated with the help of new operator
Destructor
• Used to destroy objects that have been
created by a constructor
• The destructor is a member function whose
name is the same as the class name but is
preceded by a tilde (~)
• A destructor never takes argument, nor does
it return any value
Lets Practice
• Write a C++ program to demonstrate the following concepts
in a class named Person:
– A default constructor that initializes name to “Your Name” and age to 0.
– A parameterized constructor that takes name and age as arguments.
– A copy constructor that creates a new object by copying the data from an
existing Person object.
– A destructor that displays a message when an object is destroyed.
– A display() function to print the name and age of the person.
• In the main() function:
– Create an object using the default constructor.
– Create another object using the parameterized constructor.
– Create a third object using the copy constructor (copying the second object).
– Call the display() function for all objects.

You might also like