The Design of Software (CLOSED)

A public forum for discussing the design of software, from the user interface to the code architecture. Now closed.

The "Design of Software" discussion group has been merged with the main Joel on Software discussion group.

The archives will remain online indefinitely.

C++ inheritance and copy ctor

What would stop a C++ copy ctro calling the copy ctor of it's base class?

class B :    public A
{
    B(const B &l);
    B &operator  =(const B &l);
}

B::B(const B &l)
{
  //copy all the members of B
}

B &B::operator=(const B &l)
{
  //copy all the members of B
  return *this;
}

But none of the members of A copied ?

I know this is a stupid error, as is posting under my real id! I'm just having a braindead few days.
Martin Send private email
Friday, August 10, 2007
 
 
have you tried this

class B :    public A
{
    B(const B &copythis);
}

B::B(const B &l) : A(copythis)
{
  //copy all the members of B
}
Jon
Friday, August 10, 2007
 
 
Yes, but that's only valid for the copy ctor not the assignment operator.
Actually I don't need an explicit assignment operator, the default shallow copy will do.  I just wondered how to copy the base memebrs in an assignment.
Martin Send private email
Friday, August 10, 2007
 
 
You can copy them explicitly like this:

B &B::operator=(const B &l)
{
  A::operator=(l);

  // copy all the members of B
  return *this;
}
Michael G Send private email
Friday, August 10, 2007
 
 
Thank you, I've been over in the relative sanity of Python for a while!
Martin Send private email
Friday, August 10, 2007
 
 
The amazing thing about C++ is that there actually is a solution for everything.  There are thousands of little details and corner cases and they thought of them all.  If I didn't know any better and someone said that C++ was either:

an official standard made by a group of highly respected programmers and implemented by several compilers

or

a single compiler that behaves as it behaves, and handed down by Moses 2.0 that just works because God wills it

I would believe the second.  I love C++.
Tom C
Friday, August 10, 2007
 
 
In that case, there is no correct and simple solution.

Mixing value based semantics and (public) inheritance hardly makes any sense.

Think about what would be the correct behaviour when writing:
Base b;
Derived d;
b = d;
d = b;

As most of the time we don't really need to write such assignement (or even copies), we disable the assignement (and even the copy).

In the very few cases we still need to have a value semantics on polymorphic hierarchies, there is the envelop-letter idiom. IIRC, Adobe.ASL also propose a solution with their "Regular Objects".
Luc Hermitte Send private email
Monday, August 13, 2007
 
 

This topic is archived. No further replies will be accepted.

Other recent topics Other recent topics
 
Powered by FogBugz