• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 283
  • Last Modified:

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?
   
0
hshliang
Asked:
hshliang
1 Solution
 
chensuCommented:
Yes, it does. The derive object is a kind of CBase since CDerive is derived from CBase.
0
 
SampsonCCommented:
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.
0
 
chensuCommented:
Oops, looking at your code again, there is something wrong. Shouldn't it be

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

base[4] = &derive;
0
Never miss a deadline with monday.com

The revolutionary project management tool is here!   Plan visually with a single glance and make sure your projects get done.

 
ufolk123Commented:
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
0
 
LucHoltkampCommented:
ufold123 is correct
0
 
KangaRooCommented:
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.
0
 
hshliangAuthor Commented:
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.
0

Featured Post

Never miss a deadline with monday.com

The revolutionary project management tool is here!   Plan visually with a single glance and make sure your projects get done.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now