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!