C++ Nested classes or member classes
Inheritance is the mechanism of derived certain properties of one class into another. The c++ language supports yet another way of inheriting properties of one class into another.
That is a class can contain objects of other classes as its members as shown below example
class alpha
{
……
……
};
class beta
{
………
………
};
class gamma
{
alpha a;
beta b;
…….
…….
};
|
all objects of gamma class will contain the object a and b. This kind of relationship is called nesting. creation of an object that contains the another object is very different than the create of an independent
object. An independent object is created by its constructor whenever it is declared with arguments. on the other hand, a nested object is created in two stages, First the member object are created using their respective constructors and then the other ordinary members are created.
This means constructors of all the member object should be called before its own constructor body is executed. This is accomplished using an initialization list in the constructor of the nested class.
Example
class gamma
{
………
alpha a;
beta b; <
public:
gamma(arglist):a(arglist1),b(arglist2)
{
}
};
|
arglist is the list of arguments that is to be supplied when a gamma object is defined. These parameters are used for initialization the members of gamma. arglist1 variable is the argument list for the constructor of a and variable arglist2 is the argument list for the constructor of b.
arglist1 and arglist2 may or may not use the arguments from arglist. Remember a(arglist1) and b(arglist2) are function calls and therefore the arguments do not contain the data types. They are simply variables or constants.
Example gamma( x, y, z):a(x), b(x,z)
{
assignment section(for ordinary other members)
}
|
we can use as many member objects as are required in a class. for each member object we add a constructor call in the initializer list. The constructor of the member object are called in the order in which they are declared in the nested class.