using a function in a derived class to change a base class' private data member?
I have a practice question as below.
Considering the following code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
|
class One{
public:
void print() const;
protected:
void setData(string,char);
private:
string str;
char ch;
};
class Two: public One {
public:
void print() const;
void setData(string,char,int);
private:
int val;
};
|
When the following function is used:
1 2 3 4 5 6 7
|
int main() {
Two bb;
bb.setData("Exam",'A',60);
bb.print();
}
|
the output is:
Exam A 60
1. Write the definition of the member function print of class Two.
2. Write the definition of the member function setData of the class Two.
NOTE: assume the base class One has all its member functions defined.
So the code that I have works ONLY if 'str' and 'ch' in the base class are NOT private:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
|
#include <iostream>
using namespace std;
class One{
public:
void print() const;
protected:
void setData(string s,char c) {
this->str = s;
this->ch = c;
}
string str;
char ch;
};
class Two: public One {
public:
void print() const {
cout << this-> str << " " << this->ch << " " << this->val << endl;
}
void setData(string s,char c ,int v) {
this->str = s;
this->ch = c;
this->val = v;
}
private:
int val;
};
int main() {
Two bb;
bb.setData("Exam",'A',60);
bb.print();
}
|
I know that it's not possible for the derived class to access the base class private members, but I'm not sure how else to answer the question?
Appreciate the help, am study fatigued so might be overlooking something.
You could call One's setData function from Two's setData function.
1 2 3 4
|
void setData(string s, char c, int v) {
One::setData(s, c);
this->val = v;
}
|
Last edited on
You're meant to make use of One's functions when dealing with One's data:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
|
#include <string>
#include <iostream>
using std::string;
using std::cout;
class One{
public:
void print() const
{
// QUESTION STATES THAT ONE'S FUCTIONS ARE IMPLEMENTED
cout << str << ' ' << ch;};
}
protected:
void setData(string a,char b)
{
// QUESTION STATES THAT ONE'S FUCTIONS ARE IMPLEMENTED
str = a; ch = b;
}
private:
string str;
char ch;
};
class Two: public One {
public:
void print() const
{
One::print();
cout << ' ' << val;
};
void setData(string a,char b,int c)
{
One::setData(a, b);
val = c;
};
private:
int val;
};
int main() {
Two bb;
bb.setData("Exam",'A',60);
bb.print();
}
|
Last edited on
Just what I wanted, thanks! I didn't know you could do that.
Topic archived. No new replies allowed.