user1135137
user1135137

Reputation:

Declaring a class with a custom constructor in another class

I have a class whose only constructor accepts an integer, and I would like to use it in another class without making it a pointer and using new/delete.

Is this even possible?

Relevant parts of first class:

class A
{
  private:
  int size; 
  char *c;

  public:
  A(int i)
  {
    size = i;
    c = new char[i];
  }
  ~A() { delete[] c; }
}

And I want to use it in an example class B as follows:

class B
{
  private:
  A a(7); // Declaration attempt #1
  A b; //Declaration attempt #2
  A *c; //This is what I'll do if I have no other choice.

  public:
  B()
  {
    b = A(7); //Declaration attempt #2
    c = new A(7);
  }
}

Upvotes: 0

Views: 162

Answers (1)

David G
David G

Reputation: 96800

In-class initialization of an object using () is not possible because it gets interpreted as a function declaration. You can use the member-initializer list to do this instead:

class B
{
    A a;

    public:
        B() : a(7)
    //      ^^^^^^
        {}
};

This would also work with assignment inside the constructor but the member-initializer list is recommended because initializes instead of assigns.

In C++11 you can use uniform-initialization:

class B
{
    A a{7};                                                                    /*
    ^^^^^^^                                                                    */

    public:
        B() = default;
};

Upvotes: 3

Related Questions