lundi 18 juin 2018

Why I can't uses proteced method? Error: "'void A::printToScreen() const' is protected"

given the following code:

class A {
protected:
    void printToScreen() const;
public:
    A() = default;
    virtual ~A() {
    }
    virtual void Print() const=0;
};

void A::printToScreen() const {
    std::cout << "printToScreen" << std::endl;
}

class B: public A {
public:
    B() = default;
    void Print() const override;
};

void B::Print() const {
    std::cout << "Print_B" << std::endl;
    A* a = new B();
    this->printToScreen();  // OK
    a->printToScreen(); // *****error*****
}

And for example:

A* a = new B();
    a->Print();  

I get the following error:

'void A::printToScreen() const' is protected

But I don't understand what it's not correct in my code. printToScreen is protected, but, I uses this method In a class inherited from A , so what it's the problem?

In addition, what is the different between this->printToScreen(); to a->printToScreen(); ? it's seen same (while I talking about the access to protected methods)

Aucun commentaire:

Enregistrer un commentaire