-1

Assume the following:

class A {
    public: 
        A();
    protected:
        int a;
};

class B : public A {
    public: 
        B();
};

My questions:

  • Can I access (directly) the protected data members of A and maybe modify them without having to use public member functions?
  • Can I treat A inside B as an "existing" object so that I can return A by reference and be able to modify its data member?

I am new to C++. I tried couple things to treat "A" as an object but I keep getting error messages. Here is one thing I have tried:

A & B::getA() {
    return A; //error: "A does not refer to a value"
}
Olank1969
  • 3
  • 3

2 Answers2

1

Can I access (directly) the protected data members of A and maybe modify them without having to use public member functions?

A protected member variable or function is very similar to a private member but it provided one additional benefit that they can be accessed in child classes which are called derived classes.

Can I treat A inside B as an "existing" object so that I can return A by reference and be able to modify its data member?

In B you can directly access to A (public and protected) method and attributes.

Read here for more.

Community
  • 1
  • 1
granmirupa
  • 2,780
  • 16
  • 27
0

To return a reference to your base class you can write

A & B::getA() {
    return *this;
}

to access A's protected data member you can simply write

a = 5;
πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190