+ 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(); }
13 odpowiedzi
+ 3
price, weight are private variables in class Product so can't access outside of that class ....
+ 2
Create a Constructor in super class to set those private values and call that constructor in base class constructor..
+ 2
A simple workaround would be to implement info in the derived class only and provide a virtual function in the base class.
+ 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
+ 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
+ 1
Thanks. The code as to be all changed. You're great Jayakrishna.
+ 1
I think that taking your first code and replacing private: by protected: is simpler
+ 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.
0
I know that Jayakrishna. So how i gonna call those variables in derived class?
0
Maybe delete setinfo, delete obj.setinfo and void a type method.
0
Thanks also to vcoder.
0
This is what I said 😑
- 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.