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

StackOverflow https://stackoverflow.com/questions/22175325

  •  03-06-2023
  •  | 
  •  

سؤال

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?

هل كانت مفيدة؟

المحلول

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) {}

نصائح أخرى

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

class B
{
public:
    B(int x, double y) : a(x) {}
private:
    A a;
};

int main()
{
    B b(23, 78.6);
}

You can use an initialiser list to do this. See http://en.cppreference.com/w/cpp/language/initializer_list

You can call the constructor from your B-class, but you have to supply a value to A's constructor.

An example could be this:

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

class B{
public:
    B( void ) : _my(0){};
private:
    A _my;
};

Alternatively, you could pass a value from B on to A, by e.g.

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

class B{
public:
    B( int x_b ) : _my(x_b){};
private:
    A _my;
};

I don't know if this exactly solves your problem, but it will make your class a private class of B, without the need of creating pointers and the whole new/delete part that comes with it.

Cheers

Either of the two options you suggested is fine. Which one you should choose will depend on your use-case. Generally I'd prefer the first option while ensuring that you delete A in B's destructor. You should only use an init() method if you ensure that A will correctly report an error if it is used without being initialized.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top