Important Introduction to Programming Short Questions
Chapter: 29
Question 1:
Can a function outside a class declare itself as a friend of the class?
Answer:
No, a function cannot declare itself a friend of a class; the class itself must declare the function as a friend.
Chapter: 29
Question 2:
What is the difference between a friend function and a member function?
Answer:
A friend function is not a member of the class but can access private data, whereas a member function is a part of the class and can access private data.
Chapter: 29
Question 3:
How does a friend function access the private data members of a class?
Answer:
A friend function accesses private data members through an object of the class passed as an argument.
Chapter: 29
Question 4:
Can two classes be friends with each other?
Answer:
Yes, one class can be declared as a friend of another, allowing its functions to access the private members of the other class.
Chapter: 29
Question 5:
What is the syntax for declaring a friend class?
Answer:
The syntax is friend class ClassName; within the class definition.
Chapter: 29
Question 6:
What happens when you try to access a private data member with a non-friend, non-member function?
Answer:
The compiler will produce an error, as non-friend, non-member functions cannot access private data members.
Chapter: 29
Question 7:
What does the keyword friend signify in C++?
Answer:
The friend keyword allows a non-member function or another class to access the private and protected members of the class in which it is declared.
Chapter: 29
Question 8:
How does the placement of the friend function declaration affect its access to private data?
Answer:
The placement of the friend function declaration (public or private section) does not affect its access to private data.
Chapter: 29
Question 9:
In what file is the friend function typically declared in C++?
Answer:
The friend function is typically declared in the header file of the class.
Chapter: 29
Question 10:
What does the concept "friendship is granted, never taken" mean in C++?
Answer:
It means that a class must explicitly declare a function or class as its friend; external functions cannot declare themselves friends.