1

Can we create an array of objects of the class not having default constructor, if yes then can anyone elaborate on how can we do this?

For following class for Abc a[10] in main(); is generating compiler error 'no matching function for call to `Abc::Abc()'

class Abc{ private: int x; public: Abc(int a){ x = a; } }; int main(){ Abc a[10]; // Compilation would fail here, as it would look for default constructor } 

2 Answers 2

9

Can we create an array of objects of the class not having default constructor?

Yes, you can. You have to call one of the available constructors to initialize each of the members of the array. The only way to do that is to initialize the array with an initialization list:

Abc a[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; 

In this case, it is enough to put integers in the array, because your Abc constructor is not explicit. This means you can do this:

Abc a = 42; // Calls A(42) 

If it were explicit, you would have to say

Abc a[10] = { Abc(1), Abc(2), ..... }; 

Obviously this dosn't scale well, but it works OK for small arrays.

Sign up to request clarification or add additional context in comments.

8 Comments

This is not the only way. Look at my answer at the bottom.
@Krypton No this isn't the only way. But it has the virtue of not producing undefined behaviour.
I don't want to keep arguing for nothing. I will just keep my downvote as long as I see "The only way to do..."
@Krypton It is the only way to initialize an array of objects of a certain type. Your answer doesn't even do that.
Well, I really don't want to argue with u. Can you please read the question again? "Can we create an array of objects of the class not having default constructor" The OP didn't even mention that he wants to intialize. While my answer doesn't even do that, but I know it can. I didn't want to add as the OP did not ask for it.
|
2

The problem is that if you define a constructor, of any kind, the compiler will not automatically generate a default constructor. You have to do it manually.

2 Comments

That was a typo while writing a question, Constructor is named Abc.
@Shrikant It's a constructor, but it's not a default constructor.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.