Basically, I have a class called VisaMux and a class called MuxPath. MuxPath has a VisaMux private instance variable. I want MuxPath's constructor to assign the instance variable a given VisaMux object without invoking an empty VisaMux() constructor.
5 MuxPath::MuxPath(const uint& Clk_sel, const uint& Lane_sel, const VisaMux& Mux){
6 clk_sel = Clk_sel;
7 lane_sel = Lane_sel;
8 mux = Mux;
9 }
This code results in the error:
MuxPath.cpp:5: error: no matching function for call to ‘VisaMux::VisaMux()’
VisaMux.h:20: candidates are: VisaMux::VisaMux(const std::string&, const uint&, const uint&, const std::vector<VisaLane, std::allocator<VisaLane> >&, const std::vector<VisaResource, std::allocator<VisaResource> >&)
As you can see, it errors on the first line (line 5), so it seems that somehow const VisaMux& Mux is invoking VisaMux(), which doesn't exist. This also happens if I just do VisaMux Mux.
I don't want it to call an empty constructor for VisaMux because I want VisaMux to be created only by passing its constructor all the necessary parameters.
How can I do this?
Use the constructor initialization list:
MuxPath::MuxPath(const uint& Clk_sel, const uint& Lane_sel, const VisaMux& Mux)
: clk_sel(Clk_sel)
, lane_sel(Lane_sel)
, mux(Mux)
{}
Use member-initialization-list in the constructor as:
MuxPath::MuxPath(const uint& Clk_sel, const uint& Lane_sel, const VisaMux& Mux)
:clk_sel (Clk_sel),lane_sel(Lane_sel),mux(Mux)
{ //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ it's called initialization-list
}
Actually, in your code, all the member variables use assignment rather than their respective constructor, which means mux tries to get constructed with default constructor, even before it enters into the constructor of MuxPath. And sinceVisaMux doesn't have default constructor, its giving compilation error.
So by using the initialization-list, in which the syntax mux(Mux) invokes the copy-constructor of VisaMux, you avoid the invocation of default constructor of VisaMux which doesn't exist. And since the mux is already copy-constructed, there is no need to use assignment in the constructor body.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With