Even though Builder
is declared inside of DerivedClass
, Builder
is not implicitly friends with DerivedClass
, like you are expecting. Builder
is still its own class, and it follows the same rules as any other class, including scope access rules. That is why DerivedClass
cannot access protected
members of Builder
by default. You need to explicitly declare that friendship.
Also, your Builder::Description()
method will not work as-is because Builder
does not have a description
member. The this
pointer inside of Builder
methods still refers to the Builder
instance, not a DerivedClass
instance. If you want the Builder
to access members of DerivedClass
, it needs to be given a pointer to a DerivedClass
instance. Otherwise, give Builder
its own description
member (which it looks like you were attempting to do anyway).
Try this:
BaseClass.h:
class BaseClass
{
protected:
CString name;
};
DerivedClass.h:
class DerivedClass : public BaseClass
{
public:
class Builder : public BaseClass
{
public:
Builder(const CString &pName)
{
this->name = pName;
}
Builder& Description(const CString &pDescription)
{
this->description = pDescription;
return *this;
}
public:
CString description; // <-- add this
friend class DerivedClass; // <-- add this
};
public:
DerivedClass(const Builder &builder);
public:
CString description;
};
DerivedClass.cpp:
DerivedClass::DerivedClass(const DerivedClass::Builder &builder)
{
this->name = builder.name; // this is ok now
this->description = builder.description; // this is ok now
}