Constructors

Discussion in 'C++' started by Andrea Crotti, Oct 27, 2010.

  1. 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?
     
    Andrea Crotti, Oct 27, 2010
    #1
    1. Advertising

  2. Andrea Crotti

    Ian Collins Guest

    On 10/27/10 10:13 PM, Andrea Crotti wrote:
    > 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.

    --
    Ian Collins
     
    Ian Collins, Oct 27, 2010
    #2
    1. Advertising

  3. 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; }
    };
     
    Yakov Gerlovin, Oct 27, 2010
    #3
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Dave Rudolf
    Replies:
    12
    Views:
    8,303
    Martijn Lievaart
    Feb 6, 2004
  2. Jeremy Smith
    Replies:
    2
    Views:
    590
    Jeremy Smith
    Aug 3, 2006
  3. Jess
    Replies:
    5
    Views:
    609
    Ron Natalie
    Jun 7, 2007
  4. Peng Yu
    Replies:
    5
    Views:
    399
    Juha Nieminen
    Sep 19, 2008
  5. srp113
    Replies:
    3
    Views:
    470
Loading...

Share This Page