简体   繁体   中英

Call parent constructor with private members in parent class

It is possible to call the parent constructor having the members of it in private? I know that with protected this works, but I prefer to use private, is there any way to solve this?

class Product {

    std::string id;
    std::string description;
    double rateIVA;

public:
    Product(std::string id, std::string description, double rateIVA);
    ~Product();

    // Abstract Methods / Pure Virtual Methods
    virtual double getIVAValue() = 0;
    virtual double getSaleValue() = 0;

    // Virtual Method
    virtual void print() const;

    // Setters & Getters
    void setId(std::string id);
    std::string getId() const;
    void setDescription(std::string description);
    std::string getDescription() const;
    void setRateIVA(double rateIVA);


    double getRateIVA() const;
};

class FixedPriceProduct : protected Product {

    double price;

    public:
        FixedPriceProduct();
            FixedPriceProduct(double price); // Implement here
        ~FixedPriceProduct();

        double getIVAValue();
        double getSaleValue();

        virtual void print() const;
};

If the parent's constructor is public or protected , then there is no problem with calling it, even if the members it is initializing are private. Although it is not clear how your example will initialize the parent, so I'll just write something simpler to make things clearer:

class Parent {
    int mem_;

public:
    Parent(int mem) : mem_(mem) { }
};

class Child : public Parent {
public:
    Child(int mem) : Parent(mem) { }
};

The above example will work, no problem. The catch is that if you want to modify the mem_ member using the Child class, you can only do so using the public and protected accessor methods that the Parent class provides.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM