Unnamed objects formed during derivation
Abstract classes i.e classes which have at least one pure virtual function do not allow object instantiation. But when we derive a con开发者_运维技巧crete class from this abstract class and define all the pure virtual functions, we can instantiate an object of this class.
But when derived object is created, first an unnamed base class object has to be created. How does this happen? I mean how can this unnamed abstract base class object be created, if its creation is not allowed.
That's like saying the human heart can't exist as it needs the human. But when we create a human we must first create the heart but how do we create the heart when it can't exist without the human.
The answer is because we create them together they are all part of a single entity.
The heart and human are created together.
No object actually exists until the constructor fully completes at which point heart and human exist as a single object.
You have confused “not possible” with “not allowed”. Instantiation of abstract classes is possible for compiler, of course; it's just not allowed to programmer.
when derived object is created, first an unnamed base class object has to be created. How does this happen?
IMO, base class object is not created in the way we see. Yes we do provide constructor and methods etc in base class, but they are merely tools for initialization/assignments.
In actual, derived class is inheriting base part of it, so ultimately we are creating derived class object only. Analogical example:
struct B {
int b;
virtual void foo() = 0;
};
struct D : B {
int d;
virtual void foo () {}
};
While creating object, compiler looks D
as,
struct D {
int b,d;
virtual void foo () {}
};
It sees that D
is fulfilling all the conditions to be able to instantiate an object and it creates the object.
精彩评论