Private methods suddenly inaccessible when chaining

c++

Solution

A protected member in a class is accessible from a derived class only through that derived class, i.e. through an object of, or reference or pointer to, that derived class.

The return type of `A()` is `Base*`, which is not the derived class, which is why you can't access its protected members. The compiler doesn't track that it really refers to the same object.

Problem

I have a simple class hierarchy with a base class and a derived class. The base has two protected members that the derived class calls. Coming from some recent C# experiences, I thought it would be good to make the interface a bit more fluent and allow chaining of method calls, so instead of calling `this->A()`, then `this->B()` you can call `this->A()->B()`. However, the following code will not compile: ``` #include <iostream> class Base { protected: Base* A() { std::cout << "A called." << std::endl; return this; } Base* B() { std::cout << "B called." << std::endl; return this; } }; class Derived : public Base { public: void Test() { // Base::A and Base::B are private here. this->A() // This works fine ->B(); // Suddenly I cannot access my own private method? } }; int main() { Derived d; d.Test(); return 0; } ``` This produces the following compiler error: ``` main.cpp: In member function 'void Derived::Test()': main.cpp:12:15: error: 'Base* Base::B()' is protected Base* B() ^ main.cpp:26:21: error: within this context ->B(); // Suddenly I cannot access my own private method? ^ ``` I also tried making the base class methods virtual, but that didn't help. My C++ is rusty enough that I can't seem to figure out what is going on here, so help would be much appreciated. Also I was wondering if this is a bad idea because `C++ != C#` and C++-people aren't used to such fluent interfaces.

Original source