Home print sum of data members of child classes in parent function
Reply: 2

print sum of data members of child classes in parent function

Allen M
1#
Allen M Published in 2017-03-12 20:40:39Z
#include <iostream>
using namespace std;


class Fruit {

protected:
int nr_fruits = 0;

public:
void printTotal() {
    cout << "Total fruits in the basket: " << nr_fruits << endl;
}

};


class Mango : public Fruit {

int nr_mangoes;

public:

void getMango(int x) {
    nr_mangoes = x;
    cout << "There are " << nr_mangoes  << " mangoes in the basket" <<  endl;
    nr_fruits = nr_fruits + nr_mangoes;

}
};

class Apple : public Fruit {

int nr_apples;

public:

void getApple(int x) {
    nr_apples = x;
    cout << "There are " << nr_apples << " apples in the basket" <<  endl;
    nr_fruits = nr_fruits + nr_apples;
}
};



int main(int argc, const char * argv[]) {

Apple a1;
Mango m1;

a1.getApple(10);
a1.printTotal();
m1.getMango(20);
m1.printTotal();

return 0;

}

I need to make a function in the parent class Fruit, to be able to print the number of total fruits, in my case, nr_mangoes + nr_apples.

Obviously, the way i do it, the nr_fruits variable will output only the amount of mangoes or the amount of apples as the total amount of fruit.

How can i get to access the data members of the child classes, or make the variable nr_fruits so that it keeps the value throughout the program.

Fanarosss
2#
Fanarosss Reply to 2017-03-12 20:54:14Z

In this case you need the use of inheritance. You will use virtual functions.

You will have to store in a vector of pointers to fruit, all the fruits you have.

vector<Fruit*> MyFruits;

Inside class Fruit you will implement a virtual function:

virtual int get_num_of_fruits(){}

And inside the child classes:

int get_num_of_fruits(){
    return nr_child; //nr_apples,nr_mangos etc.
} 

Then you will have an int nr_fruits = 0 and add to the number of all the fruits(apples,mangos etc.)

So, nr_fruits += MyFruits[i]->get_num_of_fruits(); for i = 0 to i<MyFruits.size()

amallard
3#
amallard Reply to 2017-03-12 21:17:49Z

In the case of your example and for simplicity, you can change your nr_fruits variable to be static, then initialize it after the class declaration:

class Fruit {
    public:
        static int nr_fruits;
        void printTotal() {
            cout << "Total fruits in the basket: " << nr_fruits << endl;
        }
};
int Fruit::nr_fruits = 0;

However, without knowing the full scope of the requirements for your program, I think you may want to consider to design a better approach to your problem...

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.322011 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO