0
Candidate::Candidate ()
{

}

Its not doing any thing. Not writing it as it is can't execute the line:

Candidate *list = new Candidate [10];

Why?

Error: no default constructor exists for the class "Candidate"
3
  • And you're sure your candidate class actually has a constructor that has no parameters or all default parameters? Anyway, I'd suggest std::vector. Commented Dec 1, 2012 at 18:34
  • 1
    The compiler have answered your question very well :) Commented Dec 1, 2012 at 18:35
  • Look in your class definition, are you sure you define a constructor? I'm with @chris I'd use vectors also Commented Dec 1, 2012 at 18:36

2 Answers 2

2

To allow your dynamic array allocation, new Candidate[10], a default constructor of Candidate must be available. That is, it must be able to take no arguments. If you provide any of your own constructors for Candidate, regardless of how many arguments they take, the implicit default constructor that is usually defined automatically by the compiler will not be defined. You therefore have to provide it yourself, even if its body is empty. See §12.1/5:

A default constructor for a class X is a constructor of class X that can be called without an argument. If there is no user-declared constructor for class X, a constructor having no parameters is implicitly declared as defaulted (8.4).

Your class would be fine as follows because the compiler will implicitly define a defaulted default constructor:

class Candidate
{ }; // Compiler provides a default constructor

But as soon as you give it any other constructor, the implicit default constructor is not provided any more:

class Candidate
{
 public:
  Candidate(int x);
  // A user-defined constructor is provided so the default constructor
  // must be defined explicitly
};
Sign up to request clarification or add additional context in comments.

Comments

1

You probably have an additional constructor in your class. If you have any constructor defined, the compiler won't generate a default one.

4 Comments

You mean to say when ever I define a constructor that is not a default, I must give definition of default with it too?
Basically, yes - if you want to allow creating instances of your class without passing parameters (it won't be called "default" in this case because you define it manually, just a constructor with no parameters)
It's still called the default constructor, because it is called by default when no argument list is provided. The differentiating term is "compiler-generated".
@icepack It's still a default constructor, just not a defaulted default constructor (unless you = default it).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.