Reputation: 5471
I have a doubt regarding some concept of inheritance, i am stating what i know, please correct me if i am wrong.
Private members of base class are inherited by the derived class but derived class can't access them by any means.
Protected members of base class are inherited by the derived class but derived class can't access it directly, but by the help of some of its member functions.
Now in the following code:
class A
{
protected:
A(const A&){}
A operator=(const A &){}
int t;
public:
A(int r) {t=r;}
A(){t=0;}
};
class B : public A
{
A a;
public:
void make(void)
{
//A b(a); //LINE 1 -------COPY CONSTRUCTOR BEING CALLED ---protected member of base class
cout<<t; //LINE 2 -------protected member of base class
}
};
int main()
{
B b;
b.make();
return 0;
}
Why there is error for LINE 1 coming??
Why we can't call copy-constructor for object of A?
Many many thanx in advance
Upvotes: 1
Views: 346
Reputation: 355357
A protected member can only be accessed by other members of the same complete object, during construction, destruction, or via the this
pointer(*).
In your example class hierarchy, a B
object has two subobjects of type A
:
A
, anda
, which it gets by declaring a
.A member of B
may only access protected members from the first A
subobject, not from the second, because only the first directly uses the this
pointer (note that your expression cout << t
is semantically equivalent to cout << this->t
).
Access to the members of the data member do not directly use the this
pointer: if you tried to access this->a.t
from B::make
, the this
pointer is not used directly to access the t
. In your declaration A b(a);
, the copy constructor is called not for this
, but for the new A
object you are constructing, the local variable named b
.
(*) Or, of course, by any member in the class that declares it: any member function of B
can call any other member function of B
Upvotes: 5