Frage

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?

War es hilfreich?

Lösung

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

Andere Tipps

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.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top