Reputation: 4075
I'm a new user of programming c++. When I don't create a derived instance by new, it calls Base::test(). So what is the difference between Base b = d and Base* b1 = new Derived() ?
Base class
#include <iostream>
class Base
{
public:
virtual void test() { std::cout << "Base::test()" << std::endl; };
};
Derived class
#include "Base.h"
class Derived : public Base
{
public:
void test() { std::cout << "Derived::test()" << std::endl; };
}
main.cc
#include "Derived.h"
int main()
{
Derived d;
d.test();
Base b;
b = d;
b.test(); // why called Base::test() ?
Base* b1 = new Derived();
b1->test();
delete b1;
return 0;
}
Upvotes: 2
Views: 1207
Reputation: 13
You have mesh between two important concept in c++.
In c++ run time polymorphism is achieved using base class pointer with the help of virtual function. Since actual type of object is decided at run time. As we know base class pointer can store object of derived class. And then call to any function invoke call to derived class function(if base is virtual).
In you case you are assigning object of derived class to object of base class. This is Object slicing.
Upvotes: 0
Reputation: 15824
Derived d;
d.test();
Base b;
b = d;
b.test(); // why called Base::test() ?
You created a Derived
object d
and Base
object b
. And later assigned b=d;
Here object slicing is happening. After the assignment b
has only Base
part of the Derived
class info in hand. So when you call b.test()
it will call Base::test()
instead Derived::test()
function.
Base* b1 = new Derived();
b1->test();
delete b1;
Here you dynamically created a Derived class object in heap and returned the pointer of that object to Base class pointer. Here pointer is nothing but the memory address holding the Derived
class object. And when you call b->test()
, system internally identify the type of the object dynamically and it is returned as Derived
. So it will call Derived::test()
function.
Upvotes: 4
Reputation: 1668
Because that's not how polymorphism is implemented in C++.
This:
Base b;
b = d;
the second statement calls an assignment operator of b, i.e. b is still the same object b of class Base (except perhaps the data is now different, but the set of methods, i.e. the type is still Base).
You need to operate on pointers instead of references, because references cannot be changed and they are not changed.
Upvotes: 0