Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does C++ force me to define a default constructor

I come from a c#/scala/java world and am recently develloping in c++ so please excuse if this is a dumb question.

When I declare a member variable in a class which should be initialized at some point at run time. For example if the member variable wraps functionality of a network device for which the user has to specify the address. After the user entered the address I would create the DeviceWrapper instance. My class would look something like this:

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

When declaring the member variable it is my understanding that the default constructor of DeviceWrapper gets called if I don't explicitly call it in the constructor of A. However for the DeviceWrapper class it doesn't make sense to have a default constructor as the class is pointless without knowing the address of the device to wrap.

Am I missing something here or does C++ force me to either define a pointless default constructor in DeviceWrapper or make the class mutable so that the wrapper can receive its address after its creation?

Another alternative would be to make dev a 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 a pointer to the instance. This concept would be broken if I define dev as DeviceWrapper* dev;

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

like image 411
mgttlinger Avatar asked Mar 26 '26 13:03

mgttlinger


1 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 the construction of A. They all have different copy semantics, and you need to choose which makes sense for your application.

like image 81
Bill Lynch Avatar answered Mar 29 '26 01:03

Bill Lynch