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).
Thank you !
CodePudding user response:
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.