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?
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
Customerproperly initializes itsCustomerIdmember in the initializer list, with thecustomer_id_(a)call. Take that away, or add a default constructor forCustomerand you will get an error. For example:In the code you have shown, the default constructor for
Customeris implicitly deleted (because you have defined another one), so there is no way that aCustomerobject can be created without there being an appropriate call to the (non-default) constructor for the embeddedCustomerIdobject.