Thread: base class pointer to derived class objects

  1. #1
    Registered User
    Join Date
    Jul 2003
    Posts
    450

    base class pointer to derived class objects

    can you reassign a base class pointer to various derived class objects.

    ie
    BaseClass *ptrBaseClass=new BaseClass;
    *ptrBaseClass=*ptrFirstDerivedClass;
    *ptrBaseClass=*ptrSecondDerivedClass;
    etc.

  2. #2
    Registered User
    Join Date
    May 2003
    Posts
    148

    Re: base class pointer to derived class objects

    Originally posted by curlious

    BaseClass *ptrBaseClass=new BaseClass;
    *ptrBaseClass=*ptrFirstDerivedClass;
    *ptrBaseClass=*ptrSecondDerivedClass;
    etc.
    That is called object slicing,not good.

    That is correct
    Code:
    BaseClass *ptrBaseClass=new BaseClass;
    ptrBaseClass = ptrFirstDerivedClass;
    ptrBaseClass = ptrSecondDerivedClass;

  3. #3
    Registered User
    Join Date
    Jul 2003
    Posts
    450
    Thanks!
    I thought about it after I posted and wasn't sure weather *ptr could even be an l-value.

  4. #4
    Registered User jlou's Avatar
    Join Date
    Jul 2003
    Posts
    1,090
    Code:
    BaseClass *ptrBaseClass=new BaseClass;
    ptrBaseClass = ptrFirstDerivedClass;
    ptrBaseClass = ptrSecondDerivedClass;
    While that is the correct way to make a base class pointer point to a derived class, it is of course a memory leak if used the way shown above, since the BaseClass object created with new will be lost without being destroyed.

  5. #5
    Registered User
    Join Date
    May 2003
    Posts
    1,619
    Originally posted by curlious
    Thanks!
    I thought about it after I posted and wasn't sure weather *ptr could even be an l-value.
    Yes. * means "the object pointed at by". For example:

    Code:
    int * i = new int;
    *i = 25;
    delete i;
    i has type "int *", *i has type "int".
    You ever try a pink golf ball, Wally? Why, the wind shear on a pink ball alone can take the head clean off a 90 pound midget at 300 yards.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. base class pointer pointing at derived class
    By mynickmynick in forum C++ Programming
    Replies: 11
    Last Post: 12-01-2008, 12:26 PM
  2. Replies: 9
    Last Post: 06-20-2008, 02:41 AM
  3. Replies: 25
    Last Post: 10-29-2007, 04:08 PM
  4. derived class can not access base class protected member?
    By George2 in forum C++ Programming
    Replies: 2
    Last Post: 10-21-2007, 06:32 PM
  5. simple question
    By SuperNewbie in forum C++ Programming
    Replies: 2
    Last Post: 01-24-2005, 03:03 PM