-2

Hello I am new to C++ and learning the conversion from a base class pointer to a derived class pointer.

class Base{
public:
    virtual void method(){
        std::cout << "this is a base class" << std::endl;
    }
};

class Derived:public Base{
public:
    virtual void method(){
        std::cout << "this is a derived class" << std::endl;
    }
};


int main(){
    Base *a = new Base();
    Derived *b = new Derived();
    a = b
    a->method() 

    Base c;
    Derived d;
    c=d;
    c.method() 

    return 0;
}

a->method() will print "this is a derived class"

c.method() will print "this is a base class""

How to understand the different behavior? I kind of understand that a = b basically let the compiler know a is a Base class pointer pointing to Derived class, so the polymorphism will work here. But what does c=d do in the code?

I am using Xcode..

Thanks in advance!

cgao
  • 155
  • 4
  • 15

1 Answers1

2

The c = d line does what's called slicing - it takes the base part of d and copies it to c, slicing off all the properties of the derived class. This includes any virtual functions defined in the derived class.

If you want polymorphism, you must use a pointer or reference.

Mark Ransom
  • 299,747
  • 42
  • 398
  • 622
  • Thanks Mark. I am really not good at relating my specified questions to the existing well-known magic words in c++... `slicing` solves my question! – cgao Sep 24 '14 at 15:11
  • @Mahone glad I could help! Sometimes in this business the terminology is the hardest part... Google works wonders when you know which words to use. – Mark Ransom Sep 24 '14 at 15:24