Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 994
pixartist Avatar asked Jun 26 '26 21:06

pixartist


1 Answers

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) {}
like image 173
Sebastian Redl Avatar answered Jun 30 '26 14:06

Sebastian Redl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!