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

For the questions below, assume that initially baseClass has only an integer x a

ID: 3695221 • Letter: F

Question

For the questions below, assume that initially baseClass has only an integer x as a private data member, and the derived class has only an integer y as a private data member. You need to provide the class definition and any function member needed i.e. set/get for each data member, constructor, destructor, etc., as well as he appropriate access modifier i.e. public, private, protected, static, virtual, friend, etc.

Write a function printParentValue() in the derived class that will access directly the value of x, and will print it on the screen; and a function printChildValue() which is not a member function of either base or derive class, but can access y directly and display its value on the screen.

Explanation / Answer

#include<iostream>
#include<cstdlib>

using namespace std;

// base class
class baseClass{
   // protected members, so that it can be accessed by child class directtly
   protected:
       int x;
      
public:
       static int count; // static member to keep count of number of objects
       // constructor
       baseClass(int x){
           this->x = x;
           cout<<"This is class "<<x<<endl;
           count++;
       }
      
      
       int getCount(){
           return count;
       }
      
       void print(){
           cout<<x<<endl;
       }
      
       // getter and setter
      
       void setX(int x){
           this->x = x;
       }
      
       int getX(){
           return x;
       }
};

// initializing static count variable
int baseClass::count = 0;

// derived class
class derivedClass: public baseClass{
   private:
       int y;
   public:
       derivedClass(int x, int y):baseClass(x){
           this->y = y;
           cout<<"This is class "<<y<<endl;
       }
      
       void print(){
           cout<<y<<endl;
       }
      
       void setY(int y){
           this->y = y;
       }
      
       int getY(){
           return y;
       }
      
       // printing x directly
       void printParentValue(){
           cout<<x<<endl;
       }
       // friend function
       friend void printChildValue(derivedClass* d);
};

// defination of friend function
void printChildValue(derivedClass* d){
   cout<<d->y<<endl;
}

int main(){
  
   derivedClass *m = new derivedClass( 56, 14 );
  
   baseClass *n = new baseClass( 79 );
  
   m->print();
   n->print();
  
   cout<<"Count value: "<<m->getCount()<<endl;
  
   printChildValue(m);
  
}

/*

Output:

This is class 56
This is class 14
This is class 79
14
79
Count value: 2
14

*/

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote