assignability & class tree

V

viki

There is tree of classes rooted at CBase (single-inheritance). CSub is
derived from CBase, and CBase having virtual member functions, (and
other classes derived from CBase or CSub). All classes must be
assignable.
But much of the code accesses these object through CBase* pointers.

Now, having two CBase* pointers to two objects of actual type CSub,
how do I make assignment smoothly
work through the base-class pointers ? (assigning objects, not
pointers) ?

My question is how can I write assignment operators so as to make the
following to just work:

CBase *x = new CSub;
CBase *y = new CSub;
*x = *y; // how to write assignment operators so that this
will work correctly ?

Is this possible ?

Thanks Viki
 
A

Alf P. Steinbach

* viki:
There is tree of classes rooted at CBase (single-inheritance). CSub is
derived from CBase, and CBase having virtual member functions, (and
other classes derived from CBase or CSub). All classes must be
assignable.
But much of the code accesses these object through CBase* pointers.

Now, having two CBase* pointers to two objects of actual type CSub,
how do I make assignment smoothly
work through the base-class pointers ? (assigning objects, not
pointers) ?

My question is how can I write assignment operators so as to make the
following to just work:

CBase *x = new CSub;
CBase *y = new CSub;
*x = *y; // how to write assignment operators so that this
will work correctly ?

Is this possible ?

It's possible but it involves dynamic type checking, which you can see from the
assignment expression: the dynamic types are not known at compile time and *may*
be incompatible, and in that case, what do you want the assignment effect to be?

Dynamic type checking complicates things so much that it's simply a Very Bad Idea.

Instead you should make a choice: either assignable, or polymorphic, but not both.

If you choose to make the classes assignable and non-polymorphic you may opt to
disable dynamic allocation, which you can do e.g. by restricting access to the
class' allocation function (which quite misleadingly is called 'operator new').

Conversely, if you choose to make the classes polymorphic you can and should in
general choose to restrict access to assignment. In that case you may opt to
support cloning. That is, instead of the above you'd write something like

Base* x = new Sub;
Base* y = x->clone();

Except that you shouldn't really be using raw pointers. :)


Cheers & hth.,

- Alf
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,967
Messages
2,570,148
Members
46,694
Latest member
LetaCadwal

Latest Threads

Top