Search code examples
c++oopdefault-constructor

Should I use pointers to OOP objects or should a create default constructors?


I'm really confused about c++ objects. If an object has to be initialized with parameters (which most objects do), should I create a constructor with parameters and thus always create pointers to my objects when storing them, or should I have an empty constructor with an Init() method which takes the parameters necessary to initialize my objects so that I can have non-pointer fields for my objects?

EDIT: I mean this:

//A.h
class A
{
    public:
        A(int x);
}
//B.h
class B
{
    private:
        A myobject;
}

Will throw IntelliSense: no default constructor exists for class "A"

So I can do this:

//B.h
class B
{
 private:
  A* myobject;
}

OR

//A.h

class A
{
 public:
  A(void);
  void Init(int x);
}

which of those is the right thing to do?


Solution

  • The initializer list feature exists precisely so that you can pass arguments to the constructors of members.

    class B {
      A a;
    public:
      B();
    };
    
    B::B() : a(99) {}