Link to home
Start Free TrialLog in
Avatar of hshliang
hshliang

asked on

Add a derived class to an array of base class.

Is is possible to add/change one member of an array of base classes as/to a derived class.

e.g.  CBase* base = new CBase[5];
      CDerive derive;

base[4] = &derive.

does this work?
   
ASKER CERTIFIED SOLUTION
Avatar of chensu
chensu
Flag of Canada image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of SampsonC
SampsonC

Yes it is possible, but not a good idea.  The problem is that when you iterate through the array, the compiler is counting on everything being sizeof(CBase).  If you throw a CDerive object in there, it's going to throw it off and be most likely unpleasant.
Oops, looking at your code again, there is something wrong. Shouldn't it be

CBase **base = new CBase *[5];
CDerive derive;

base[4] = &derive;
or may be you want to write it as

CBase* base = new CBase[5];
CDerive derive;
base[4] = derive.

This is a problem as compiler will strip off the derive to a object of type base.So you will not be able to invoke any of derive class functionality from base[4] element .


Ideally you should do like.

CBase*  base[5];

// for i =1 to 4 fill base[i] with new CBase
 
base[4] = new derive.

Now you can take advantage of polymorphic behaviour by

base[i]->func().

for base[4] func for derived class will be called,as expected.

Regards,
ufolk123
ufold123 is correct
You should avoid using arrays of objects from class hierarchies. You can use pointers to objects.
So [A]
   Base * a = new Base[5];
   // an array of objects.
is asking for trouble. Take a look at:
   Base* b = new CDerived[5];
Perfectly legal, probably deadly.

Now [B]
   Base** a = new Base*[5];
   // should be fine

From [A] you then do
   Cderived d;
   a[4] = &d;
So you try to assign the _pointer_ to a CDerived object to a Base _object_
This is ok for [B].

From [A] doing
    a[4] = d;
will use the assignmnet operator of class Base. This could be fine, but a[4] will still be a Base object.
From [B]
    a[4] = new CDerived;
    a[3] = new Base;
is fine, a[4] contains a pointer to a CDerived while a[3] holds a pointer to a Base object. This is probably what you want.
Avatar of hshliang

ASKER

Thank you for all the suggestion. It now works well for me. Yes, it is better to have an array of pointers, as I do need specific function of the derived.