Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why do I need a constructor function?

#include<iostream>
using namespace std;

class A {
public:
    int i;
};

int main() {
  const A aa;  //This is wrong, I can't compile it! The implicitly-defined constructor does not initialize ‘int A::i’
}

when I use

class A {
public:
  A() {}
  int i;
};

this is ok! I can compile it! why I can't compile it when I use the implicitly-defined constructor?

like image 612
funs Avatar asked Oct 01 '13 08:10

funs


People also ask

Why do we need a constructor function?

A constructor is a special function that creates and initializes an object instance of a class. In JavaScript, a constructor gets called when an object is created using the new keyword. The purpose of a constructor is to create a new object and set values for any existing object properties.

What is a constructor & why is it used for?

In class-based object-oriented programming, a constructor (abbreviation: ctor) is a special type of subroutine called to create an object. It prepares the new object for use, often accepting arguments that the constructor uses to set required member variables.

Why do you need constructors in C++?

C++ Constructors. Constructors are methods that are automatically executed every time you create an object. The purpose of a constructor is to construct an object and assign values to the object's members. A constructor takes the same name as the class to which it belongs, and does not return any values.


1 Answers

why the implicit-defined constructor does not work?

It does work, but one of the language rules is that it can't be used to initialise a const object unless it initialises all the members; and it doesn't initialise members with trivial types like int. That usually makes sense, since being const there's no way to give them a value later.

(That's a slight simplification; see the comments for chapter and verse from the language standard.)

If you define your own constructor, then you're saying that you know what you're doing and don't want that member initialised. The compiler will let you use that even for a const object.

If you want to set it to zero, then you could value-initialise the object:

const A aa {};    // C++11 or later
const A aa = A(); // historic C++

If you want to set it to another value, or set it to zero without the user having to specify value-initialisation, then you'll need a constructor that initialises the member:

A() : i(whatever) {}
like image 136
Mike Seymour Avatar answered Sep 22 '22 03:09

Mike Seymour