(1) Yes, we can only access grandparents members in derived class when we inherit it either using public or protected access modifier.
(2) Base Class members declared as protected are inaccessible outside the class , but they can be accessed by any derived class of that class . When you inherit protected members of base class via public or protected access modifier , that data members access specifier is protected in the derived class .
(3) By default access modifier is private in C++ in inheritance which is in your given example . Since, you are trying to access private members of base class in child class , it is bound to give compile time error . Please read next point also.
(4) Base Class members declared as private are of course inherited to derived class . But , they are not accessible irrespective of the access modifier used while inheriting . It is the matter of availability v/s accessibility . Private members of base class are available to subsequent derived class but are not accessible . We can check this using sizeof(derived class object) operator after privately inheriting base class .
Lets discuss another thing .How do we access private members of base class ?
Well , we can do that by using friend functions and pointers . But , Declaring Friend function inside base class depends on the creator of that base class . So , we wont talk about that in this post .
class Base
{
private :
int x1,x2;
};
class Derived : public Base
{
public :
int x3;
void display(int *ptr)
{
cout << "the value of x1 = " << *(ptr) << endl;
cout << "the value of x2 = " << *(ptr+1) << endl;
cout << "the value of x3 = " << *(ptr+2) << endl;
}
};
int main()
{
Derived d;
int *ptr = (int *)&d.x3; // typecasting
*ptr = 3; // setting x3 as 3
ptr--;
*ptr = 2; // setting x2 as 2
ptr--;
*ptr = 1; // setting x1 as 1
ptr--;
d.display(ptr);
return 0;
}
We have succesfully accessed private members of base class .
One more thing is there that i want to share is that : if we have a virtual grand parent class , we can directly call the grand parent constructor from child class . But in general it is not allowed to call grandparents constructor directly , it has to be called through parent classs . It is allowed only when virtual keyword is used .
struct
are public by default. In fact, the only difference between aclass
and astruct
is thatclass
members are private by default andstruct
members are public by default. – Perse