Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Please, answer the questions in c++ Module 6: Working with Classes Questions Que

ID: 3868685 • Letter: P

Question


Please, answer the questions in c++

Module 6: Working with Classes Questions Question1 Does a nonmember function have to be a friend to access a class's members? Question.2 What class methods does the compiler generate automatically if you don't provid,e them explicitly? Describe how these implicitly generated functions behave. Question 3 Identify and correct errors in the following class declaration class nifty ll data char personalityl: int talents l methods nifty0 nifty(char s); ostream & operator

Explanation / Answer

Answer 1:

Yes it is true that a non member function have to be a friend to access a class's members

Answer 2

Following methods will be generated automatically if not given expliciltly:
1.Default Conctructor
2.Copy Constructor
3.Copy-assignment operator
4.Destructor

Answer 3.

1.No access specifiers are mentioned. The default access specifier is private in c++.Better to mention access specifiers.

2.The function declaration outside the class is not correct.
nifty:nifty(char *s) - it should be nifty::nifty(char *s). Similarly for other funnctions.

3.ostream & opeartor <<(ostream & os,nifty &n);
Also the function body should include return os; statement

4.At the end of the class definition, there should be a semicolon ;

5.personality = NULL
personality = new char[strlen(s)]

Both the above statement give error. The correction will be personality should be declared as
char *personality;

6.Constructor must be deifined public

7.ostream &operator<<(ostream &os,nifty &n); should be declared as
friend ostream &operator<<(ostream &os,nifty &n);

The corrected class declaration is as follows:


class nifty {
   //data
private:
   char *personality;
int talents;
//methods
public:
nifty();
nifty(char *s);
friend ostream &operator<<(ostream &os,nifty &n);
};
nifty::nifty()
{
   personality = NULL;
   talents = 0;
}
nifty::nifty(char * s)
{
   personality = new char[strlen(s)];
   personality = s;
   talents = 0;
}

ostream &operator<<(ostream &os,nifty &n){
os << n;
return os;
}