Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I alloc member value with "Get" function?

Here’s a simple code.

class Sub
{
    ...
public:
    Sub()
    {
        ...
    }
}

class Main
{
private:
    Sub*    m_pSub

public:

    Main()
    {
        // I don't want construct "Sub" here
        m_pSub = nullptr;
    }    

    Sub*    GetSub()
    {
        return m_pSub;
    }
}


/////////////////////
// in source
Main*   pMain;

pMain->GetSub() = new Sub()

Of course, pMain->GetSub() = new Sub() does not work because the left value of ‘=’ in the above code must be a correctable value.

Therefore, please teach me various ways to implement similarly
(which can be used as short as possible).

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Thank you !

>Solution :

The simplest way to make your code work is to have GetSub() return a reference, eg:

class Main
{
private:
    Sub* m_pSub = nullptr;

public:

    Main() = default;

    Sub*& GetSub()
    {
        return m_pSub;
    }
};

However, this isn’t very good class design.

Another option is to have GetSub() create the object on its first call, eg:

class Main
{
private:
    Sub* m_pSub = nullptr;

public:

    Main() = default; 

    Sub* GetSub()
    {
        if (!m_pSub) m_pSub = new Sub;
        return m_pSub;
    }
};

Otherwise, use an explicit setter method, eg:

class Main
{
private:
    Sub* m_pSub = nullptr;

public:

    Main() = default;    

    Sub* GetSub()
    {
        return m_pSub;
    }

    void SetSub(Sub* newSub)
    {
        m_pSub = new Sub;
    }
};

...
pMain->SetSub(new Sub);

Either way, you really should be using smart pointers, either std::unique_ptr or std::shared_ptr, to make it clear who owns the Sub object and is responsible for destroying it. A raw pointer does not convey that information.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading