Reputation: 1929
i have this code snippet
#include <iostream>
using namespace std;
class Polygon
{
public:
int publicmemberPolygon;
private:
int privatememberPolygon;
protected:
int protectedmemberPolygon;
};
class Square : public Polygon
{
public:
int Getter();
};
int Square::Getter()
{
return privatememberPolygon;
}
int main()
{
}
problem is, why is privatememberPolygon is inaccesbile? isnt it, when you have a dervied class, all of its members/functions are copied? thanks
Upvotes: 1
Views: 457
Reputation: 73443
No, when you derive publicly from a base class, only its public
and protected
members are accessible for the derived class. You can also read this FAQ.
See this example:
class Base
{
public:
void setPrivate(int p)
{
m_private = p;
}
public:
int m_public;
protected:
int m_protected;
private:
int m_private;
};
class Derived : public Base
{
public:
void f()
{
m_public = 0; // Can access public member of base class
m_protected = 0; //Can access protected member of base class
m_private = 0; //Compiler error- Can not access private member of base class
}
};
int main() {
Derived d;
d.setPrivate(10); //m_private is still part of the derived class. Hence can call setPrivate
return 0;
}
Upvotes: 3
Reputation: 2640
Only the public and the protected data members are accessible in inheritance when your inheriting publicly.
Upvotes: 2
Reputation: 283664
Members are not "copied" to the derived class. The derived class contains a subobject of the base class, almost the same as if you have a member variable.
In fact, composition and non-public inheritance are often considered two paths to solve the same problem.
A trivial difference, with non-public inheritance, is that members of a base subobject don't have to be qualified by an object name to find them, they're part of this (unless you have diamond inheritance, yuck!). With public inheritance, there's also an implicit conversion from a pointer or reference to the derived class into a pointer or member to the base class.
The bigger difference is that inheritance allows overriding virtual functions, while composition does not.
And protected
members (and bases) are practically useless in the final analysis, since they inhibit composition without providing a real benefit the way that virtual
does. Sometimes they're used when virtual functions already make inheritance a necessity.
Upvotes: 2