jon wayne said:
OK!
I had this nagging doubt
Consider (without worrying abt access specifiers)
class Kid : public Parent{...};
Parent::someFunc()
{
Kid k;
}
ISSUE- this new Kid , while constructing it, can't I make the
parent of this new kid point to the already existing parent.
What do you mean by "parent of"? Using class names which are the same as
concepts (such as parent, meaning the specific class "Parent", as well as
the generic meaning "base class", sometimes also called "parent class"),
makes it difficult to determine what you're referring to.
There are two kinds of parent-child relationships (disregarding your class
names for the moment). One is inheritence, which you've shown, where some
people refer to the base class as the parent class.
There is also the "tree" relationship, where a "parent node" contains
pointers to one or more "child nodes", and a "child node" often contains a
pointer to its "parent node". If that's what you're talking about, then you
should not be using inheritence here. So I'll assume you're talking about
inheritence...
The Kid class has no "pointer" to a "parent", at least not in the code
you've shown. It is derived from Parent, and can be considered to actually
_be_ a Parent in this case (since you've used public inheritence).
When you create a Kid object, memory is allocated for a Kid object. Then,
the constructor for the Parent class initializes that part of the new Kid
object which is declared within the Parent class. Then, the constructor for
the Kid class is executed, initializing any members which were declared in
the Kid class itself.
So you personally don't create a Parent object, and then create a Kid
object. If you want a Kid object, then you just create one. Because you've
defined Kid as a class publicly derived from Parent, a Kid object can also
be treated as a Parent object (if you're using a reference or pointer
variable). That's called polymorphism. But there's no "pointer" to a
Parent object inside the Kid object. It's just part of the Kid object.
DO we
REALLY NEED to create a Parent each time a Kid object is created.
You don't do that, the compiler does that. You've declared Kid as being
derived from Parent, so every member that is declared within the Parent
class is _automatically_ part of a Kid object as well.
But, if you really _want_ a pointer to a Parent object inside your Kid
object, then you're talking about a whole different subject, and you
probably didn't want to use inheritence in the first place.
-Howard