1

I'm trying to pass a pointer that points to a Derived class to a Base class constructor when creating an object. Here is the scenario:

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; }
 };

In main.cpp:

...

Derived derived;

...

1 . Why does it print out the exact same memory for base_ptr and derived_ptr, but a different method of Foo() is called for each constructor ?

2 . If in initializer list for Derived() instead of Base(this) i do Base(derived_ptr), why does it pass in some junk ?

user17789
  • 21
  • 2
  • Look at virtual call in constructor/destructor. – Jarod42 Sep 26 '16 at 20:55
  • Take a look at [this list](http://stackoverflow.com/q/388242/2069064). There's a lot you have to learn about initialization order and how `virtual` works. – Barry Sep 26 '16 at 20:57
  • For 2: You may got warning for `derived_ptr(this), Base(this)` which is in fact `Base(this), derived_ptr(this)`, and so `Base` constructor is called before `derived_ptr` initialization. – Jarod42 Sep 26 '16 at 20:59
  • 1
    As a rule of thumb - the only thing you are allowed to do with a pointer to a derived class in the constructor of the base class is store it but **not** use it in any way. And even that earns you a warning, usually. – BitTickler Sep 26 '16 at 21:02

0 Answers0