From what I have learned in class, derived classes do not inherit their parent class's:
- Constructors/Destructors
- Friends
- Private Members
However if we upcasted the derived class to its parent class, would we have access to the private members of the parent class and would the Parent class's friends now apply to this upcasted class?
I am inclined to think the upcasted derived class will not be able to access the parent's private methods and variables since there is a reason the derived class does not inherit them in the first place.
(Below code was added after the verified answer was verified)
This c++ code was used to test the question I asked:
#include <iostream>
class A;
void funcGetAVal(A);
class A
{
private:
int aVal;
friend void ::funcGetAVal(A);
public:
A()
{
aVal = 0;
}
};
class B : public A
{
public:
int bVal;
B() : A()
{
bVal = 0;
}
};
void funcGetAVal(A aClass)
{
std::cout << "A val accessed from friend function: " << aClass.aVal << std::endl;
}
int main()
{
B * b = new B;
A * a = new A;
A * bNowA = reinterpret_cast<A *>(b); //This reinterprets the instance of the derived class into an instance of the base class
//std::cout << bNowA->aVal << std::endl; //This caused a compile-time error since aVal is a private member of A
::funcGetAVal(*a); //This calls the funcGetAVal function with an instance of the base class
::funcGetAVal(*bNowA); //This calls the funcGetAVal function with an instance of the derived class reinterpreted as the base class
//Both funcGetAVal function calls print out 0
return 0;
}
The results are in line with R Sahu's answer. Access of the private member of A from an instance of B caused an error, and the friend function was able to access the derived class's aVal.