Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
246 views
in Technique[技术] by (71.8m points)

c++ - Abstract class accessing its child class functions

Is it possible to access the child's function members from a pointer of an abstract class as the parent? This is the abstract class

class Item {
    public:
        virtual double getTotalPrice() = 0;
};

This is the child class

class Product : public Item {
    protected:
        string name;
    public:
        Product() {}
        string getName() {}
        double getTotalPrice() {}
};

Is it possible in the main driver to access this getName() function from an instance of the Item class, as I want to display the total price and the name of the product also?

question from:https://stackoverflow.com/questions/66060925/abstract-class-accessing-its-child-class-functions

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
  • You need your base class to have a virtual destructor if you should be able to delete objects through a base class pointer.
  • Make getName virtual too.
class Item {
public:
    virtual ~Item() = default;
    virtual const string& getName() /* const */ = 0;
    virtual double getTotalPrice() /* const */ = 0;
};

Note that the Product class that you aren't allowed to change is slightly flawed.

  • It doesn't return values where it should.
  • The getter member functions are not const.

Suggest some changes if you can't do it yourself:

class Product : public Item {
private: // prefer private member variables
    string name;
public:
    Product() = default;
    const string& getName() const override { return name; }
    double getTotalPrice() const override {
       // why is this implemented here when there's no price to return?
       return {};
    }
};

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...