cppforlife wrote:
I have a question about using 'has a' inheritance. I want to know how
to extend class that had been used in another class. What i mean is if
i have AddressBook class and its private member AddressRecord class
how i can extend AdressRecord class without changing member of
AdressBook
There are several implications by this existing design. First of all,
if 'AddressRecord' was meant to be extended, then 'AddressBook' must
have already been designed to accommodate that, by, for example, not
keeping the instances of 'AddressRecord' by value but keeping them by
pointers (or references). If that's so, then all you need to do is to
make sure your new class adheres to LSP by implementing the true "is-a"
relationship to 'AddressRecord'.
class AddressRecord;
class AddressBook{
public:
//...
private:
//...
AddressRecord* add;
What's that? A dynamic array of AddressRecord objects? Then it won't
work. It has to be a dynamic [collection] of 'AddressRecord' pointers
if you want to keep the same implemenation of 'AddressBook' for the
entire 'AddressRecord'-base hierarchy.
};
class AddressRecord{
//..
};
if i will inherit from AddressRecord class i should change private
member od AddressBook class but it violates OCP(open closed
principle).
I strongly recommend you re-examine the reasons why you need the changes
of which you're asking. Why do you need to derive something from the
'AddressRecord' class? It seems that the 'AddressBook'-'AddressRecord'
pair of types wasn't meant to be extended...
How can i do that dynamiclly using OOP and if i use
templates is it good?
template<class T>
class AddressBook{
public:
//...
private:
//...
T* add;
};
Here you're re-implementing 'AddressBook'. Yes, that's possible. This
is what is known as "compile-time polymorphism". Again, there has to
be a reason for everything. Why do you need 'AddressBook' a template?
Do you plan using it for yet unknown types like 'AddressRecord'?
V