+ 3

How to solve this (Inherinted fruit c++)

#include <iostream> using namespace std; class Product { private: double price; int weight; public: void info() { cout <<price<<", "<<weight; } }; class Fruit : public Product { public: string type; void setInfo(double p, int w) { price=p; weight=w; } }; int main() { Fruit obj; obj.type = "Apple"; obj.setInfo(4.99, 10); obj.info(); }

27th Dec 2021, 6:31 PM
Norberto Costa
Norberto Costa - avatar
13 Respostas
+ 3
price, weight are private variables in class Product so can't access outside of that class ....
27th Dec 2021, 6:41 PM
Jayakrishna 🇼🇳
+ 2
Create a Constructor in super class to set those private values and call that constructor in base class constructor..
27th Dec 2021, 7:10 PM
Jayakrishna 🇼🇳
+ 2
A simple workaround would be to implement info in the derived class only and provide a virtual function in the base class.
28th Dec 2021, 10:37 AM
Sanjay Kamath
Sanjay Kamath - avatar
+ 2
#include <iostream> using namespace std; class Product { protected: double price; int weight; public: void info() { cout <<price<<", "<<weight; } }; class Fruit : public Product { public: string type; void setInfo(double p, int w) { price=p; weight=w; } }; int main() { Fruit obj; obj.type = "Apple"; obj.setInfo(4.99, 10); obj.info(); } Good Luck
25th Jan 2022, 7:22 PM
Muhammad Alif Deva Rizqon
Muhammad Alif Deva Rizqon - avatar
+ 1
If you want that properties and methods can be accessed only in the same class and its children ones, use protected instead of private, this should resolve your problem
27th Dec 2021, 7:10 PM
VCoder
VCoder - avatar
+ 1
Thanks. The code as to be all changed. You're great Jayakrishna.
27th Dec 2021, 7:13 PM
Norberto Costa
Norberto Costa - avatar
+ 1
I think that taking your first code and replacing private: by protected: is simpler
27th Dec 2021, 7:15 PM
VCoder
VCoder - avatar
+ 1
At line 6 you wrote private: replace that with protected In inheritance in c++ the derived class can't inherit private membrs, it will inherit protected and public only. Protected members are just like private members, both can't be accessed from outside the class but protected members can be inherited unlike private ones.
28th Dec 2021, 3:31 PM
Yvette
Yvette - avatar
0
I know that Jayakrishna. So how i gonna call those variables in derived class?
27th Dec 2021, 7:00 PM
Norberto Costa
Norberto Costa - avatar
0
Maybe delete setinfo, delete obj.setinfo and void a type method.
27th Dec 2021, 7:10 PM
Norberto Costa
Norberto Costa - avatar
0
Thanks also to vcoder.
27th Dec 2021, 7:14 PM
Norberto Costa
Norberto Costa - avatar
0
This is what I said 😑
28th Dec 2021, 3:34 PM
VCoder
VCoder - avatar
- 1
I am without patience. I would like a straight answer. Yet i think that the setInfo() method can't be called in fruit class.
27th Dec 2021, 7:08 PM
Norberto Costa
Norberto Costa - avatar