COMP 220 Homework 5 Question Analysis the following code, after each statement,
ID: 3549959 • Letter: C
Question
COMP 220 Homework 5
Question
Analysis the following code, after each statement, point out it is illegal or not, and also give the reason.
/* Base class */
class bClass
{public:
bClass(char a = '*', double b = 0.0);
char getCh();
double getD();
protected:
char ch;
private:
double d;
};
/* Derived class */
class dClass : public bClass
{
public:
dClass(char, double, int);
int getX();
private:
int x;
};
dClass::dClass(char a, double b, int c)
{
ch = a; //
d = b; //
x = c; //
}
/* Application */
int main()
{ bClass bc('*', 2.3);
cout << bc.getCh(); //
cout << bc.ch; //
cout << bc.d; //
dClass dc('?', 3.5, 8);
cout << dc.getX(); //
cout << dc.getCh(); //
cout << dc.x; //
cout << dc.ch; //
cout << dc.d; // }
Explanation / Answer
//Analysis the following code, after each statement, point out it is illegal or not, and also give the reason.
/* Base class */
class bClass
{public:
bClass(char a = '*', double b = 0.0);
char getCh();
double getD();
protected:
char ch;
private:
double d;
};
/* Derived class */
class dClass : public bClass
{
public:
dClass(char, double, int);
int getX();
private:
int x;
};
dClass::dClass(char a, double b, int c)
{
ch = a; // derived class can access protected member of base class so this line is legal.
d = b; // derived class can't access private member of base class so this line is illegal.
x = c; // x is member of derived class so derived class have access this line is legal.
}
/* Application */
int main()
{ bClass bc('*', 2.3);
cout << bc.getCh(); // this line is legal because getCh is public function in
cout << bc.ch; // this line is illegal because ch is protected member of class.
cout << bc.d; // this line is illegal because d is private member of class.
dClass dc('?', 3.5, 8); // this line is legal because constructor is public.
cout << dc.getX(); // this line is legal because getX() is public function.
cout << dc.getCh(); // this line is legal because getCh() is public function.
cout << dc.x; // this line is illegal because x is private member of class.
cout << dc.ch; // this line is illegal because ch is protected member of class.
cout << dc.d; // this line is illegal because d is private member of base class.
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.