Documente Academic
Documente Profesional
Documente Cultură
3 INHERITANCE
Queue is a super type of deque , and all the objects of a subclass such as
deque obey the subtype principle:
Queue q;
Deque d;
10.5 C++
Class LinkableObject
{
Public:
LinkableObject()
: link(0) { }
LinkableObject (LinkableObject* p)
: link(p) { }
LinkableObject* next()
{
return link;
}
Void linkTo(LinkableObject* p)
{
Link=p;
}
Private:
LinkableObject* link;
};
The reason for this notation in c++ is efficiency:c++ insists that all inatance
variables be intialised prior to the execution of the body of any
Constructor; thus, intializat Ion would be performed twice if it were expressed as code
regular inside the body of the constructor(once by the system and once by the actual
code)
Class A
{
Public:
Void p()
{
Cout<<”A: :p\n”;
}
Virtual void q()
{
Cout<<”A::q\n”;
}
Void f()
{
P();
Q();
}
};
Class B:public A
{
Public:
Void p()
{
Cout<<”b::p\n”;
}
Void q()
{
Cout<<”B::q\n”;
}
};
Int main()
{
A a;
B b;
a.f();
b.f();
a=b;
a.f();
}
A c++ program illustrating dynamic and static binding.
The inherited function A.f is called Inside this function in A are calls to p and q.since p is
not virtual,dynamic binding does not apply ,and this call is resolved at compile time to
A::p(). On the other hand,the call to q is virtual,and the implicit object parameter is used
to dynamically resolve the call during execution.Thus, the call to q is implicitly a call this
s->q(),and in the call b.f(),this is the address of b.so B::q appears on the fourth line of
the above output. On the other hand, the assingment a=b simply copied the data of b to
a and does not change the address of a or the pointer in the call to a.f().Thus,A::p and
A::q are again called.
Int main()
{
A* a=new A;
B* b=new B;
a->f();
b->f();
a=b;
a->f();
return 0;
output:
A::p
A::q
A::p
B::q
A::p
B::q
Multiple inheritance in c++ ordinarily creates separate copies of each class ona
inheritance path.
Ex:
Class A{………};
Class B:public A{…..};
Class C: public A{….};
Class D:public B,public C{….};
This is repeated inheritance.To get a simple copy of an A in class D,one must declare
the inheritnce using the virtual keyword:
Class A{…..};
Class B:virtual public A{…..};
Class C:virtual public A{…..};
Class D:public C{….};