1
class Monitor {
public:
    Monitor(string someData);
    Person person_;
}

class Person {
public:
    Person(string personId);
}

Person has no default constructor. it has one argument constructor. I can initialize it only inside Monitor constructor. I come from java where declaration is only pointer , so you don’t need to initialize new instance when you declare.

What is the best practice for class member that doesn’t has default constructor? Should i add default constructor (disadvantage - no use for it ) or use pointer .

Cœur
  • 37,241
  • 25
  • 195
  • 267
Avihai Marchiano
  • 3,837
  • 3
  • 38
  • 55

1 Answers1

7

Yes, you can, and you always should, via the constructor initializer list:

class Monitor
{
    Person p; 
    bool   state;
    const  int n;
    double & d;

    Monitor(std::string const & pname, double & dbl)
    : p(pname)
    , state(false)
    , n(some_other_function(p, state))
    , d(dbl)
    {
         // constructor body should be as short as possible
    }

    // ...

};

As you can see, initializing is not just a gimmick; rather, it's a profound necessity of the C++ type system: There are lots of variables which must be initialized and cannot be assigned to, such as constants and references, but also user-defined types without default constructor. (And even if there was a default constructor, you would need an assignment operator, and it would in any case still be wasteful to construct something you don't want just to overwrite it a moment later.)

Pay attention also to the order in which your class constituents are constructed: When you create a new instance of your class, the member objects are constructed first, in the order in which they are declared in the class definition, but initialized as specified in the initializer list. After all the members are constructed, the body of the constructor runs.

Actually, there's one other thing that is constructed even before the member objects: base subobjects. Naturally, their initializer too goes in the initializer list:

struct Foo { Foo(int, bool);               /* ... */ };
struct Bar { Bar(std::string const &, int) /* ... */ };

class Monitor : public Foo, private Bar
{
    Person p;

    Monitor(std::string const & pname, int a, int b)
    : Foo(a, a == b)
    , Bar(pname, b)
    , p(pname)
    {
        // constructor body
    }

    // ...
};

It is highly recommended (though not enforced) that you write the initializers in the constructor initializer list in the same order in which they will be executed!

Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084