Re: reference to pointer of derived class
From: Bogdan Sintoma (bogy01_at_yahoo.com)
Date: 01/27/05
- Next message: stephane: "Method PrintLn (two classes)// need help"
- Previous message: Alf P. Steinbach: "Re: Is this (tiny) function portable?"
- In reply to: Moes: "Re: reference to pointer of derived class"
- Next in thread: Moes: "Re: reference to pointer of derived class"
- Reply: Moes: "Re: reference to pointer of derived class"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Date: 27 Jan 2005 03:32:18 -0800
Hi
Moes wrote:
> Thanks for the response. The code in question is actually in the
operator=
> of a class in which I have a pointer to a pure virtual base class
(such as
> "Car" in my example). I have to set that pointer to a new derived
class
> (either new TOyota() or new Honda() in the example) depending on what
type
> the source class's member points to. how would this be achieved
without a
> switch on type?
As Jerry already told you: virtual functions.
>(In the real class it's a vector of pointers, instad of a
> single member pointer, in case that matters.)
It doesn't matter.
> struct Garage{
> Garage(){ pCar = NULL; }
Garage() : pCar(0) {}
> ~Garage(){ if( pCar ) delete pCar; } // Will this call the correct
> destructor for derived classes?
Yes, if the Car class has a virtual destructor.
And you don't need "if". If the pCar is NULL delete will do nothing. If
it is not NULL but already deleted you are in trouble anyway :).
> Garage& operator=( const Garage &source ){
> if( pCar )
> delete pCar; // may need the below switch here too so the
correct
> destructor is called?
In your "real" code did you test for self-assignment?
You should implement the op. = in terms of the copy constructor and
swap.
Or, try this:
|Garage& operator=( const Garage &source )
|{
| if( this != &source)
| {
| delete pCar;
| pCar = 0; //NULL
| if( source.pCar )
| pCar = source.pCar->clone();
| }
| return *this;
|}
Where clone() is a virtual function declared in the base class and
implemented in each class derived from Car something like:
|virtual Car* clone() const
|{
| return new ThisCarSpecificClass( *this );
|}
Here "virtual" is optional, but I prefer to write it anyway.
And by the way, please see the faq:
http://www.parashift.com/c++-faq-lite/virtual-functions.html#faq-20.6
.
.
Best regards,
Bogdan Sintoma
- Next message: stephane: "Method PrintLn (two classes)// need help"
- Previous message: Alf P. Steinbach: "Re: Is this (tiny) function portable?"
- In reply to: Moes: "Re: reference to pointer of derived class"
- Next in thread: Moes: "Re: reference to pointer of derived class"
- Reply: Moes: "Re: reference to pointer of derived class"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|