Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you use the non-default constructor for a member?

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.

like image 629
Jeremy Salwen Avatar asked Jan 18 '10 20:01

Jeremy Salwen


People also ask

What is non default 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.

How does a constructor which is a member function?

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.

What if there is no default constructor available?

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.

What happens when there is no default constructor in Java?

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.


1 Answers

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.

like image 111
i_am_jorf Avatar answered Nov 04 '22 15:11

i_am_jorf