Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declaration vs. Instantiation

Tags:

c++

oop

Comming from Java, I have difficulty with the code below. In my understanding b is just declared on line 3 but not instantiated.

What would be the text book way of creating an instance of B in class A?

class A {
  private:
    B b;
  public:
    A() { 
      //instantiate b here?
    }
};

Edit: What if B does not have a default constructor?

like image 698
user695652 Avatar asked Jul 12 '26 14:07

user695652


1 Answers

You could explicitly initialize b in A's constructor's initialization list, for example

class A {
  B b; // private
 public:
  A : b() {} // the compiler provides the equivalent of this if you don't
}; 

However, b would get instantiated automatically anyway. The above makes sense if you need to build a B with a non-default constructor, or if B cannot be default initialized:

class A {
  B b; // private
 public:
  A : b(someParam) {}
};

It may be impossible to correctly initialize in the constructor's initialization list, in which case an assignment can be done in the body of the constructor:

class A {
  B b; // private
 public:
  A {
    b = somethingComplicated...; // assigns new value to default constructed B.
  }
};
like image 123
juanchopanza Avatar answered Jul 15 '26 05:07

juanchopanza



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!