Code/Recipes/Child call parent

From Polytech Center Barcelona
Jump to: navigation, search

Parent owns child

struct parent
{
    child c;
};

struct child
{
};

Child call parent

// popup.hpp

class sendw;

class popup
{
public:
    popup(sendw* sw);

    void foo();

private:
    sendw* sw_ = nullptr;
};

// sendw.hpp
#include <string>

class sendw
{
public:
    sendw();

    void bar();

    std::string name;
private:
    popup p_;
};

// popup.cpp
#include <iostream>
#include <cassert>

popup::popup(sendw* sw)
{
    sw_ = sw;
}

void popup::foo()
{
    std::cout << "Hello!" << std::endl;
    // See 'enforce logic' with assert
    // Enforce that sw_ is not-null
    assert(sw_);

    // In some function in the popup class
    // Now we want to call some functions on sendw / get some data from it
    ///////////////////////////
    std::cout << "popup::foo(): Name is " << sw_->name << std::endl;
    // NOTE: x->y is short from (*x).y
    ///////////////////////////
}

// sendw.cpp

sendw::sendw() // After last bracket: class begins construction
  : p_(this)
    //
    // ...  Initialize and ready class members
    //
    //      NOTE:
    //      in order of declaration not the order they appear in the
    //      constructor implementation (the initialization member list order)
    //
{ // Until first open bracket ... class exists but not initialized fully yet
    // ... More automatic initialization code
} // Finished, return back

void sendw::bar()
{
    // Call the function popup::foo()
    p_.foo();
}

// main.cpp

int main()
{
    // This will fail! Because sw_ inside p is null.
    //popup p(nullptr);
    //p.foo();

    sendw sw;
    sw.name = "Rose";
    sw.bar();

    std::cout << "int main(): Name is " << sw.name << std::endl;
    return 0;
}