C ++ forces me to define a default constructor

I came from // the world and I recently announced in so please excuse if this is a stupid question.

When I declare a member variable in a class that needs to be initialized at some point during runtime. For example, if a member variable wraps the functionality of a network device for which the user must specify an address. After the user enters the address, I'll create an instance DeviceWrapper

. My class will look something like this:

class A
{
public:
  //Method to instantiate dev and other stuff
private:
  DeviceWrapper dev;
}

      

When declaring a member variable, I understand that the default constructor is DeviceWrapper

called unless I explicitly call it in the constructor A

. However, DeviceWrapper

it makes no sense for a class to have a default constructor, since the class is meaningless without knowing the address of the wrapped device.

Am I missing something or is C ++ forcing me to either define a meaningless default constructor in DeviceWrapper

, or make the class mutable so that the wrapper can get its address after it has been created?

Another alternative would be to make a dev

pointer to DeviceWrapper

. My idea of ​​using pointers to objects is that the object that owns the instance has the instance directly, and every other object that uses it but doesn't own it gets the pointer to the instance. This concept is broken if I define dev

asDeviceWrapper* dev;

So what would be the C ++ solution to solve this problem?

+3


source to share


2 answers


The simplest solution is to wrap DeviceWrapper in one of:

std::optional<DeviceWrapper> dev;
std::unique_ptr<DeviceWrapper> dev;
std::shared_ptr<DeviceWrapper> dev;

      



All three will allow you to initialize DeviceWrapper dev

after build A

. They all have different copy semantics and you need to choose which makes sense for your application.

+4


source


There are 2 cases:

  • If you don't have a constructor, you arbitrarily get a default constructor.

  • If you have defined any constructor that is not empty, then you will not get a default constructor, so if you need it, you will have to define it.

Therefore, if DeviceWrapper

it has no constructor, the default constructor will be called (which basically does nothing), if it has an empty constructor, it will be called even if you don't have a constructor in A

. but if DeviceWrapper

there is another constructor in, and there is no empty one, you will have to initialize it from the constructor A

.



like this:

A():dev(arguments){}

0


source







All Articles