Thread: Slicing

  1. #1
    Just because ygfperson's Avatar
    Join Date
    Jan 2002
    Posts
    2,490

    Slicing

    Code:
    class Base {
      virtual void some_func();
    };
    class Derived : public Base {
      virtual void some_func();
    };
    
    void func(Base& r) {
      r.some_func();
    }
    int main() {
      Derived d;
      func(dynamic_cast<Base&>(d));
    
    
    }
    Would slicing occur in this situation? If it didn't my life would be much easier.

  2. #2
    Skunkmeister Stoned_Coder's Avatar
    Join Date
    Aug 2001
    Posts
    2,572
    your using dynamic cast to go the wrong way. dynamic cast is for the case where you force a base to a derived not a derived to a base. Because a derived is always a base too assuming public inheritance you dont need a cast. Secondly as you are using base references you will get no slicing( cos your not copying) and polymorphic behaviour of some_func()
    Free the weed!! Class B to class C is not good enough!!
    And the FAQ is here :- http://faq.cprogramming.com/cgi-bin/smartfaq.cgi

  3. #3
    Just because ygfperson's Avatar
    Join Date
    Jan 2002
    Posts
    2,490
    k, thanks a lot.

  4. #4
    Just because ygfperson's Avatar
    Join Date
    Jan 2002
    Posts
    2,490
    One more thing...

    Can I assume that an object's type information is contained in the object itself, and not just managed by the compiler at compile-time?

  5. #5
    Skunkmeister Stoned_Coder's Avatar
    Join Date
    Aug 2001
    Posts
    2,572
    no. you can never assume that.
    Free the weed!! Class B to class C is not good enough!!
    And the FAQ is here :- http://faq.cprogramming.com/cgi-bin/smartfaq.cgi

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Polymorphism - "pointers" or "references"?
    By Petike in forum C++ Programming
    Replies: 10
    Last Post: 06-04-2009, 05:06 PM
  2. Polymorphism - Slicing?
    By Tonto in forum C++ Programming
    Replies: 11
    Last Post: 07-24-2006, 12:07 PM
  3. Slicing an image
    By InvariantLoop in forum Tech Board
    Replies: 1
    Last Post: 04-30-2004, 01:13 AM