I have two classes
class a {
public:
a(int i);
};
class b {
public:
b(); //Gives me an error here, because it tries to find constructor a::a()
a aInstance;
}
How can I get it so that aInstance
is instantiated with a(int i)
instead of trying to search for a default constructor? Basically, I want to control the calling of a
's constructor from within b
's constructor.
If constructors are explicitly defined for a class, but they are all non-default, the compiler will not implicitly define a default constructor, leading to a situation where the class does not have a default constructor. This is the reason for a typical error, demonstrated by the following example.
A constructor in C++ is a special 'MEMBER FUNCTION' having the same name as that of its class which is used to initialize some valid values to the data members of an object. It is executed automatically whenever an object of a class is created.
Because there is no default constructor available in B, as the compiler error message indicates. Once you define a constructor in a class, the default constructor is not included. If you define *any* constructor, then you must define *all* constructors.
The compiler automatically provides a public no-argument constructor for any class without constructors. This is called the default constructor. If we do explicitly declare a constructor of any form, then this automatic insertion by the compiler won't occur.
You need to call a(int) explicitly in the constructor initializer list:
b() : aInstance(3) {}
Where 3 is the initial value you'd like to use. Though it could be any int. See comments for important notes on order and other caveats.
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