Constructors

A

Andrea Crotti

Now, suppose that in

--8<---------------cut here---------------start------------->8---
class X
private:
ostream& out;
Other obj;
--8<---------------cut here---------------end--------------->8---

But object has a constructor that takes "out" as a parameter, which in
this step is of course not initialized.

How can I solve it? With a pointer maybe (also a reference would have
the same problem)?

Or maybe this should not happen in general?
 
I

Ian Collins

Now, suppose that in

--8<---------------cut here---------------start------------->8---
class X
private:
ostream& out;
Other obj;
--8<---------------cut here---------------end--------------->8---

But object has a constructor that takes "out" as a parameter, which in
this step is of course not initialized.

How can I solve it? With a pointer maybe (also a reference would have
the same problem)?

Or maybe this should not happen in general?

Your questions doesn't make a lot of sense, why don't you post real code?

If a reference member must be initialised in constructors.
 
Y

Yakov Gerlovin

Why not to define op<< for 'Other' class instead of passing a
reference to 'ostream' in constructor?
In this case your 'X' class can control how the instance of 'Other' is
printed.

References must be initialized in initializer list, so your X class
also has to define a constructor that takes 'ostream':

class Obj
{
ostream& out;
public:
Obj(ostream& out_) : out(out_) { out << "Obj::Obj" << endl; }
};

class X
{
ostream& out;
Obj o;
public:
X(ostream& out_) : out(out_), o(out_) { out << "X::X=" << endl; }
};
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top