nSv23
nSv23

Reputation: 449

protected members are not accessible through a pointer or object

I have 2 classes Training and Testing, where Training is the base class and Testing is the derived class of Training.

I have Testing class member function, float totalProb(Training& classProb, Training& total), which takes 2 parameters, both are Training class objects. The code:

void Testing::totalProb(Training& classProb, Training& total) {

    _prob = (_prob * ((float)(classProb._nOfClass) / total._tnClass));
    cout << "The probalility of the " << it->first << " beloning to " << classProb._classType << " is: " << _prob << endl;
}

Basically what this function does is calculate the probability of each document in test1 (an object of Testing class) belonging to class1 (an object of Training class).

All the Training class (which is the base class) variables are Protected and all the Training class functions are Public.

When I try to run test1.totalProb(class1, total); I get the error Error C2248 'Training::_probCalc': cannot access protected member declared in class 'Training'. I am unable to get around this.

Upvotes: 11

Views: 10527

Answers (2)

jaba
jaba

Reputation: 785

Please consider the following minimal example you could have created:

class Base
{
public:
    Base(int x = 0)
        :m_x(x) 
    {}
protected:
    int m_x;
};

class Derived : public Base
{
public:
    Derived(Derived& der)
    {
        this->m_x = 1; // works

        Base base;
        // int i = base.m_x; // will not work

        Derived works(base);
        int i = works.m_x; // also works            
    }

    Derived(Base& base)
        : Base(base) // Base(base.m_x) will not work
    {
    }

};

The cpp reference says the following (https://en.cppreference.com/w/cpp/language/access) in the chapter Protected member access:

A protected member of a class Base can only be accessed

  1. by the members and friends of Base
  2. by the members and friends (until C++17) of any class derived from Base, but only when operating on an object of a type that is derived from Base (including this)

Upvotes: 5

88877
88877

Reputation: 495

You are trying to access the member of an other instance of your mother class: classProb, but inheritance make you able to access protected member of your own parent class only.

One way to correcting (but it strongly depend of what you are trying to do) is to put an getter of _probClass in your Training class and call it in your test, for instance for the _probCalc member:

public:
  (Type) Training::getProbCalc() {
    return _probCalc;
  }

the to change your call in the loop:

for (it3 = classProb.getProbCalc().begin(); it3 != classProb.getProbCalc().end(); it3++)

If you are trying to acces your own member inherited by your mother instance just call them directly. For instance:

for (it3 = _probCalc().begin(); it3 != _probCalc().end(); it3++)

Upvotes: 5

Related Questions