Initialization of object in a class

73 Views Asked by At
class CustomerId{
    public:
        CustomerId(int a) : a_(a){
            std::cout << a;
        }
        
    private:
        int a_{0};
};

class Customer {

  public:
    Customer(int a): customer_id_(a){}

  private:
   CustomerId customer_id_;
};

I am sorry if this is very stupid, but I am stuck on understanding how object of a class A declared in other class B work.

In this example, we have declared CustomerId customer_id_ as a member variable in class Customer. My assumption was that I would need to create a default constructor for CustomerId because the declaration would also create an object. I was taking cues from how we can initialize primitives at the time of declaration such as a_{0} in CustomerId.

But looks like that is not the case.

Can someone help me understand how objects declared as member variables inside other classes work?

1

There are 1 best solutions below

2
Adrian Mole On BEST ANSWER

My assumption was that I would need to create a default constructor for CustomerId because the declaration would also create an object.

Not really – the declaration of a class does not create an object of that class (or any embedded members) – that's what the constructor does, when you declare an object of the containing class (or otherwise create one).

In your case, the only constructor for Customer properly initializes its CustomerId member in the initializer list, with the customer_id_(a) call. Take that away, or add a default constructor for Customer and you will get an error. For example:

class CustomerId {
public:
    CustomerId(int a) : a_(a) {
        std::cout << a;
    }

private:
    int a_{ 0 };
};

class Customer {

public:
    Customer() {}; // Error: 'CustomerId': no appropriate default constructor available
    Customer(int a) : customer_id_(a) {}

private:
    CustomerId customer_id_;
};

In the code you have shown, the default constructor for Customer is implicitly deleted (because you have defined another one), so there is no way that a Customer object can be created without there being an appropriate call to the (non-default) constructor for the embedded CustomerId object.