将指针从Derived类传递给Base类

时间:2016-09-26 20:53:30

标签: c++ pointers inheritance

我尝试在创建对象时将指向Derived类的指针传递给Base类构造函数。这是场景:

class Base
{
public:
    // Default constructor
    Base(Base* base_ptr = nullptr)
    {
        cout << base_ptr << endl;
        base_ptr->foo();
    }
    virtual void foo() { cout << "Base foo" << endl; }
};

class Derived : public Base
{
public:
    Derived* derived_ptr;

    Derived() : derived_ptr(this), Base(this)
    {
        cout << derived_ptr << endl;
        derived_ptr->foo();
    }

    virtual void foo() override { cout << "Derived foo" << endl; }
 };

在main.cpp中:

...

Derived derived;

...

1。为什么打印出base_ptr和derived_ptr完全相同的内存,但是为每个构造函数调用了不同的Foo()方法?

2。如果在Derived()而不是Base(this)的初始化列表中,我执行Base(derived_ptr),为什么它会传入一些垃圾?

0 个答案:

没有答案