Question

Programming language questions 1) In C++ what is a Friend class or Friend Function? 2) Explain...

Programming language questions

1) In C++ what is a Friend class or Friend Function?

2) Explain how each of the following languages handle Information hiding, Constructors and destructors (GIVE EXAMPLES).

a. C++

b. Objective-C

c. C#

d. Java

0 0
Add a comment Improve this question Transcribed image text
Answer #1

1) friend functions are special functions that will allow the access of private and protected members of the class.

declaration:

class className
{
friend return_type functionName(argument/s);
}

return_type functionName(argument/s)
{
// Private and protected data of className can be accessed from
// this function because it is a friend function of className.
}

example:

using namespace std;

class Distance
{
private:
int meter;
public:
Distance(): meter(0) { }
friend int addFive(Distance); //friend function
};

int addFive(Distance d) // friend function definition
{
//accessing private data from non-member function
d.meter += 5;
return d.meter;
}

int main()
{
Distance D;
cout<<"Distance: "<< addFive(D);
return 0;
}

friend classes are nothing but class which is declared as a friend can access all the member functions of the friend class becomes friend with other class.

declaration:

class A
{
private: ... .. ...
friend class B; // class B is a friend class of class A

}

class B
{
... .. ...
}

example:

#include <iostream>
using namespace std;

class MyClass
{
friend class SecondClass; // Declare a friend class

public:
   MyClass() : Secret(0){}
   void printMember()
{
cout << Secret << endl;
}
private:
int Secret;
};

class SecondClass
{
public:
   void change( MyClass& yourclass, int x )
{
   yourclass.Secret = x;
}
};

void main()
{
   MyClass my_class;
   SecondClass sec_class;
   my_class.printMember();
   sec_class.change( my_class, 5 );
   my_class.printMember();
}

2) a. c++ : information handling-

A program throws an exception when a problem shows up. This is done using a throw keyword. Assuming a block will raise an exception, a method catches an exception using a
combination of the try and catch keywords. A catch keword catches an exception
with an exception handler at the place in a program where you want to handle the
problem.A try/catch block is placed around the code that might generate an
exception.

example, which throws a division by zero exception and we catch it in catch block
#include <iostream>
using namespace std;

double division(int a, int b) {
if( b == 0 ) {
throw "Division by zero condition!";
}
return (a/b);
}

int main () {
int x = 50;
int y = 0;
double z = 0;

try {
z = division(x, y);
cout << z << endl;
}catch (const char* msg) {
cerr << msg << endl;
}

return 0;
}
Because we are raising an exception of type const char*, so while catching this exception, we have to use const char* in catch block.

constructors and destructors-

A class constructor is a special member function of a class that is executed whenever we create new objects of that class.
A constructor will have exact same name as the class and it does not have any return type at all, not even void. Constructors can be very useful for setting initial values for certain member variables

A destructor is a special member function of a class that is executed whenever an object of it's class goes out of scope or whenever the delete expression is applied to a pointer to the object of that class.
A destructor will have exact same name as the class prefixed with a tilde (~) and it can neither return a value nor can it take any parameters. Destructor can be very useful for releasing resources before coming out of the program like closing files, releasing memories etc.

#include <iostream>
using namespace std;

class Line {
public:
void setLength( double len );
double getLength( void );
Line(); // This is the constructor declaration
~Line(); // This is the destructor: declaration

private:
double length;
};

// Member functions definitions including constructor
Line::Line(void) {
cout << "Object is being created" << endl;
}

Line::~Line(void) {
cout << "Object is being deleted" << endl;
}

void Line::setLength( double len ) {
length = len;
}

double Line::getLength( void ) {
return length;
}

// Main function for the program
int main( ) {
Line line;

// set line length
line.setLength(6.0);
cout << "Length of line : " << line.getLength() <<endl;

return 0;
}

b. objective -C: information handling-

Objective-C exceptions should not be thrown whenever there is an error—try to handle the error, or use something like NSError or the NSAssert() method.
a parsing library might use exceptions internally to indicate problems and enable a quick exit from a parsing state that could be deeply recursive; however, you should take care to catch such exceptions at the top level of the library and translate them into an appropriate return code or state.
example:
NSException* myException = [NSException
exceptionWithName:@"IndexOutOfBoundsException"
reason:@"Attempted to access an array index that is out of bounds"
userInfo:nil];
@throw myException;

try and catch exception- The code in the @try block is your usual program code. The code in the @catch block is your error handling code.
example: The code in the @try block is your usual program code. The code in the @catch block is your error handling code—here, we just log the exception.
int main(int argc, char *argv[]) {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSArray *array = [[NSArray alloc] initWithObject:@"A string"];
@try {
[array nonExistentMethod];
NSLog(@"Object at index 5 is %@", [array objectAtIndex:5]);
}
@catch (NSException *exception) {
NSLog(@"Caught exception %@", exception);
}
[array release];
NSLog(@"No issues!");
[pool drain];
return 0;
}

constructors and destructors-

In Objective-C, the destructor method is named dealloc.

c. c#: information handling-


C# exception handling is built upon four keywords: try, catch, finally, and throw.

try: A try block identifies a block of code for which particular exceptions is activated. It is followed by one or more catch blocks.
catch: A program catches an exception with an exception handler at the place in a program where you want to handle the problem. The catch keyword indicates the catching of an exception.
finally: The finally block is used to execute a given set of statements, whether an exception is thrown or not thrown. For example, if you open a file, it must be closed whether an exception is raised or not.
throw: A program throws an exception when a problem shows up. This is done using a throw keyword.

example: exception when dividing by zero condition occurs-
using System;
namespace ErrorHandlingApplication
{
class DivNumbers
{
int result;
DivNumbers()
{
result = 0;
}
public void division(int num1, int num2)
{
try
{
result = num1 / num2;
}
catch (DivideByZeroException e)
{
Console.WriteLine("Exception caught: {0}", e);
}
finally
{
Console.WriteLine("Result: {0}", result);
}
}
static void Main(string[] args)
{
DivNumbers d = new DivNumbers();
d.division(25, 0);
Console.ReadKey();
}
}
}

throwing exception:
You can throw an object if it is either directly or indirectly derived from the System.Exception class. You can use a throw statement in the catch block to throw the present object as:

Catch(Exception e)
{
...
Throw e
}

constructors and destructors-

Constructors are special methods, used when instantiating a class. A constructor can never return anything, which is why you don't have to define a return type for it.

example: we have a Car class, with a constructor which takes a string as argument. Of course, a constructor can be overloaded as well, meaning we can have several constructors, with the same name, but different parameters.
public Car()
{

}

public Car(string color)
{
this.color = color;
}

destructor- a method called once an object is disposed, can be used to cleanup resources used by the object. Destructors doesn't look very much like other methods in C#. Here is an example of a destructor for our Car class:
~Car()
{
Console.WriteLine("Out..");
}
Once the object is collected by the garbage collector, this method is called.

d. java: information handling-

The exception handling in java is one of the powerful mechanism to handle the runtime errors so that normal flow of the application can be maintained.

There are mainly two types of exceptions: checked and unchecked where error is considered as unchecked exception. The sun microsystem says there are three types of exceptions:

  1. Checked Exception
  2. Unchecked Exception
  3. Error

There are 5 keywords used in java exception handling.

  1. try
  2. catch
  3. finally
  4. throw
  5. throws

example:

public class Testtrycatch2{  

  public static void main(String args[]){  

   try{  

      int data=50/0;  

   }catch(ArithmeticException e){System.out.println(e);}  

   System.out.println("rest of the code...");  

}  

}

constructors and destructors-

similar to c++

class constructor is a special member function of a class that is executed whenever we create new objects of that class.
A constructor will have exact same name as the class and it does not have any return type at all, not even void. Constructors can be very useful for setting initial values for certain member variables.

A destructor is a special member function of a class that is executed whenever an object of it's class goes out of scope or whenever the delete expression is applied to a pointer to the object of that class.
A destructor will have exact same name as the class prefixed with a tilde (~) and it can neither return a value nor can it take any parameters.

example: implements both constructor and destructor
import std.stdio;

class Line
{
public:
this()
{
writeln("Object is being created");
}
~this()
{
writeln("Object is being deleted");
}

void setLength( double len )
{
length = len;
}

double getLength()
{
return length;
}
private:
double length;
}

// Main function for the program
void main( )
{
Line line = new Line();

// set line length
line.setLength(6.0);
writeln("Length of line : ", line.getLength());

}

Add a comment
Know the answer?
Add Answer to:
Programming language questions 1) In C++ what is a Friend class or Friend Function? 2) Explain...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Java Programming Language: Find the compiling error in the following code segment. Explain what the problem...

    Java Programming Language: Find the compiling error in the following code segment. Explain what the problem is and how to fix it. public class Mark { private float value;        public float Mark(float startValue) {        value = startValue; } }

  • 2-Many programming languages facilitate programming in more than one paradigm. TRUE OR FALSE 3-If a language...

    2-Many programming languages facilitate programming in more than one paradigm. TRUE OR FALSE 3-If a language is purposely designed to allow programming in many paradigms is called a _______________ language. What term goes in the blank? A: compiled B: interpreted C: multi-access D: multi-paradigm E: procedural 4-A "Hello, World!" program is used to do which of the following? A: Configure the compiler cache for optimizing results. B: Illustrate the basic syntax of a programming language and often is the very...

  • What are constructors? Explain why they are needed in an object-oriented programming language. If inheritance takes...

    What are constructors? Explain why they are needed in an object-oriented programming language. If inheritance takes place, what is the order in which the parent and child constructors are called? Can a constructor be overloaded? Can a constructor be overridden? Explain when a destructor should be declared as virtual in C+? Explain the use of the access specifiers public, protected and private in C++. Which is the default specifier?

  • QUESTION 2: Elementary Java Programming (a) Explain what a Wrapper class is in Java and provide...

    QUESTION 2: Elementary Java Programming (a) Explain what a Wrapper class is in Java and provide an example of one and what it [06] "wraps". (b) You have been given an array of elements to search through for a particular value. [02] Which loop would you choose between a for loop and a for-each loop and why? (c) In Java what is the difference between a StringBuilder and StringBuffer? What [02] are they used for? Total: 10

  • Programming Language is Java 1. Create a class to describe a car. Include fields like: make,...

    Programming Language is Java 1. Create a class to describe a car. Include fields like: make, model, year and color. Add all the accessors and mutators for these fields. Add a constructor that can initialize the fields. 2. Create a class that will enable you to handle standard mail communication with a customer. Add all accessors and mutators, as well as a constructor. Add a method named fullAddress that will return the address formatted for a standard mail. Add a...

  • c++ programming language Instructions In this exercise, you will design the class memberType. Each object of...

    c++ programming language Instructions In this exercise, you will design the class memberType. Each object of memberType can hold the name of a person, member ID, number of books bought, and amount spent. Include the member functions to perform the various operations on the objects of memberType—for example, modify, set, and show a person’s name. Similarly, up-date, modify, and show the number of books bought and the amount spent. Add the appropriate constructors. Write the definitions of the member functions...

  • PROGRAMMING LANGUAGE OOP'S WITH C++ Functional Requirements: A jewelry designer friend of mine requires a program...

    PROGRAMMING LANGUAGE OOP'S WITH C++ Functional Requirements: A jewelry designer friend of mine requires a program to hold information about the gemstones he has in his safe. Offer the jewelry designer the following menu that loops until he chooses option 4. 1. Input a gemstone 2. Search for a gemstone by ID number 3. Display all gemstone information with total value 4. Exit ------------------------------------- Gemstone data: ID number (int > 0, must be unique) Gem Name (string, length < 15)...

  • In the Pascal programming language, the If-Statement is defined as follows: Consider the following statement, and...

    In the Pascal programming language, the If-Statement is defined as follows: Consider the following statement, and then answer the related questions: <If-Statement> ::= If <Condition> Then <Statement> [Else<Statement>] <Statement> ::= <If-Statement> | <While-Statement> | <For-Statement> | <Assignment-Statement> <Condition> ::= [not] <Condition> | [not] <BooleanVariable> | <Variable> <Operator> Variable> | <Variable> <Operator> <Expression> | < Expression > <Operator> <Variable> | < Expression > <Operator> < Expression> | < Expression > <Operator> < Literal > | <Variable> <Operator> < Literal > <Operator>...

  • Please complete these C programming questions. Thanks you kindly True/False 1. C is a programming language...

    Please complete these C programming questions. Thanks you kindly True/False 1. C is a programming language 2. C is used only in academic settings 3. C syntax is based on Python 4. C in the acronym ASCII refers to the C language 5, C is a valid name for a variable name 6. C is the character result of 'B' +1

  • programming languages in #f language QUESTION 4 Consider the following skeletal C program: void funi(void); /*...

    programming languages in #f language QUESTION 4 Consider the following skeletal C program: void funi(void); /* prototype */ void fun2(void); /* prototype */ void fun3(void); /* prototype */ void main() { int a, b, c; void fun1(void) { int b, c, d; void fun2 (void) { int c, d, e; void fun3(void) { int d, e, f, Assuming that dynamic scoping is used, what variables are visible during execution of the last function called in following calling sequence: main calls...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT