Inheritance, member of the class orfriend

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hi All,
I have a question regarding about inheritance and member of the class. For
example I have the class A and class B what is the situation that I need to
define class B is base class of class A or class B is member of class A like
below:
Scenario 1:
class A : public B
Scenario 2:
or
class A
{
private:
B myB;
......
}
or
Scenario 3
class A
{
public :
friend class B
.......
}
Please help me to understand what are different between 3 scenario.
Thanks in advance
JP
 
Jodie said:
Hi All,
I have a question regarding about inheritance and member of the class. For
example I have the class A and class B what is the situation that I need
to
define class B is base class of class A or class B is member of class A
like
below:
Scenario 1:
class A : public B
Scenario 2:
or
class A
{
private:
B myB;
......
}
or
Scenario 3
class A
{
public :
friend class B
.......
}
Please help me to understand what are different between 3 scenario.
Thanks in advance
JP
Without knowing the specifics of the classes in question it's impossible to
speculate on whether inheritance, composition or friendship would be most
appropriate. Some very basic questions you should ask are:
Is there an "is a" relationship between the classes in question (IOW, does
it make sense to say: "An A *is a* B."?) Example: If I have a class named
Person and another named Student, it makes sense to say that a student is a
person, and that Student is a specialization of Person.
For composition, is there a "has a" relationship between the classes, does B
have an A? Example: I have an Automobile class and an Engine class. It makes
sense to say that an Automobile *has an* engine and an instance of Engine
should be a data member of Automobile.
Friendship as you've shown it gives B direct access to class A private
members, thus bypassing any safety measures built into A's public methods
for controlled access to private members of A. My personal opinion is that
you should think carefully before doing that.
I'm sure others here will elaborate and improve upon my response.
 
Back
Top