Answer to Question #344576 in C++ for khan

Question #344576

Task 1:(Inheritance and Polymorphism)

Make a class named Fruit with a data member to calculate the number of fruits in a basket. Create two other class named Apples and Mangoes to calculate the number of apples and mangoes in the basket. Print the number of fruits of each type and the total number of fruits in the basket.


1
Expert's answer
2022-05-24T13:57:30-0400
#include <iostream>
using namespace std;
class Fruit {
    static int fruitsAmount;
  
public:
    Fruit(){
        ++fruitsAmount;
    }
    ~Fruit(){
        --fruitsAmount;
    }


    static int amount(){
        return fruitsAmount;
    }
};


class Apples: public Fruit{


    static int applesAmount;
        
    public:
        Apples(){
            ++applesAmount; 
        } 
    ~Apples(){
            --applesAmount; 
        }
    static int amount(){
        return applesAmount;
    }
};


class Mangoes: public Fruit{


    static int mangoesAmount;
        
    public:
        Mangoes(){
            ++mangoesAmount; 
        } 
    ~Mangoes(){
            --mangoesAmount; 
        }
    static int amount(){
        return mangoesAmount;
    }
};
int Fruit::fruitsAmount;
int Apples::applesAmount;
int Mangoes::mangoesAmount;


int main()
{
    Apples a1, a2, a3;
    Mangoes m1,m2;
    cout<<"Apples: "<<Apples::amount()<<endl;
    cout<<"Mangoes: "<<Mangoes::amount()<<endl;
    cout<<"Fruits: "<<Fruit::amount()<<endl;
    
    return 0;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
APPROVED BY CLIENTS