Default constructor

Default constructor

In computer programming languages the term “default constructor” refers to a constructor that is automatically generated in the absence of explicit constructors (and perhaps under other circumstances); this automatically provided constructor is usually a nullary constructor. In specification or discussion of some languages, “default constructor” may additionally refer to any constructor that may be called without arguments, either because it is a nullary constructor or because all of its parameters have default values.

C++

In C++, the standard describes the default constructor for a class as a constructor that can be called with no arguments (this includes a constructor whose parameters all have default arguments).[1] For example:

class MyClass
{
    int x;
    int y;
public:
    MyClass();                                 // constructor declared
};
 
MyClass :: MyClass()                           // constructor defined   
{
    x = 100;
    y = 200;
}
 
int main()
{
    MyClass object_1;                          // object created      
}

In C++, default constructors are significant because they are automatically invoked in certain circumstances:

  • When an object value is declared with no argument list, e.g. MyClass x;; or allocated dynamically with no argument list, e.g. new MyClass; the default constructor is used to initialize the object
  • When an array of objects is declared, e.g. MyClass x[10];; or allocated dynamically, e.g. new MyClass [10]; the default constructor is used to initialize all the elements
  • When a derived class constructor does not explicitly call the base class constructor in its initializer list, the default constructor for the base class is called
  • When a class constructor does not explicitly call the constructor of one of its object-valued fields in its initializer list, the default constructor for the field's class is called
  • In the standard library, certain containers "fill in" values using the default constructor when the value is not given explicitly, e.g. vector<MyClass>(10); initializes the vector with 10 elements, which are filled with the default-constructed value of our type.

In the above circumstances, it is an error if the class does not have a default constructor.

The compiler will implicitly define a default constructor if no constructors are explicitly defined for a class. This implicitly-declared default constructor is equivalent to a default constructor defined with a blank body. For example:

class MyClass
{
    .....                                      // No Constructor          
};
int main()
{
    MyClass object_1;                          // No errors      
    ....
}

[2]

If some constructors are defined, but they are all non-default, the compiler will not implicitly define a default constructor. Hence, a default constructor may not exist for a class.This is the reason for a typical error which can be demonstrated by the following example.

class MyClass 
{
private:
    int x;
public:
    MyClass(int y);                            // A Constructor     
};
MyClass :: MyClass(int y)
{
    x = y;
}
int main()
{
    MyClass object_1(100);                     // Constructor Called           
    MyClass object_2;                          // Error: No default Constructor            
    return 0;
}

As a constructor of type other than default is defined the compiler does not define a default constructor and hence the creation of object_2 leads to an error.[3]

Java and C#

In both Java and C#, a "default constructor" refers to a nullary constructor that is automatically generated by the compiler if no constructors have been defined for the class.The default constructor is also empty, meaning that it does nothing. A user defined constructor that takes no parameters is called a default constructor too.[4][5]

References

  1. ^ C++ standard, ISO/IEC 14882:1998, 12.1.5
    C++ standard, ISO/IEC 14882:2003, 12.1.5
  2. ^ Computer Science A Structured Approach Using C++ by Behrouz A. Forouzan and Richard F. Gilberg
  3. ^ Computer Science A Structured Approach Using C++ by Behrouz A. Forouzan and Richard F. Gilberg
  4. ^ Java Language Specification, 3rd edition, section 8.8.9, "Default Constructor".
  5. ^ Using Constructors (C# Programming Guide)

Wikimedia Foundation. 2010.

Игры ⚽ Нужно решить контрольную?

Look at other dictionaries:

  • Constructor (object-oriented programming) — Programming language comparisons General comparison Basic syntax Basic instructions Arrays Associative arrays String operations …   Wikipedia

  • Constructor (computer science) — In object oriented programming, a constructor (sometimes shortened to ctor) in a class is a special block of statements called when an object is created, either when it is declared (statically constructed on the stack, possible in C++ but not in… …   Wikipedia

  • Constructor — Als Konstruktoren und Destruktoren werden in der Programmierung spezielle Prozeduren bezeichnet, die beim Erzeugen und Zerstören von Objekten oder Variablen aufgerufen werden. Konstruktoren bringen die Objekte in einen definierten Anfangszustand …   Deutsch Wikipedia

  • Constructor (informática) — El objetivo del constructor es el de inicializar un objeto cuando éste es creado. Asignaremos los valores iniciales así como los procesos que ésta clase deba realizar. Se utiliza para crear tablas de métodos virtuales y poder así desarrollar el… …   Wikipedia Español

  • Copy constructor — A copy constructor is a special constructor in the C++ programming language creating a new object as a copy of an existing object. The first argument of such a constructor is a reference to an object of the same type as is being constructed… …   Wikipedia

  • Nullary constructor — Contents 1 Object oriented constructors 1.1 Java example 2 Algebraic data types …   Wikipedia

  • Virtual Constructor — Der Begriff Fabrikmethode (englisch Factory Method) bezeichnet ein Entwurfsmuster (engl. Design Pattern) aus dem Bereich der Softwareentwicklung. Das Muster beschreibt, wie ein Objekt durch Aufruf einer Methode anstatt durch direkten Aufruf eines …   Deutsch Wikipedia

  • C++0x — is the planned new standard for the C++ programming language. It is intended to replace the existing C++ standard, ISO/IEC 14882, which was published in 1998 and updated in 2003. These predecessors are informally known as C++98 and C++03. The new …   Wikipedia

  • C++11 — C++11, also formerly known as C++0x,[1] is the name of the most recent iteration of the C++ programming language, replacing C++TR1, approved by the ISO as of 12 August 2011.[2] The name is derived from the tradition of naming language versions by …   Wikipedia

  • Comparison of C Sharp and Java — The correct title of this article is Comparison of C# and Java. The substitution or omission of the # sign is because of technical restrictions. Programming language comparisons General comparison Basic syntax Basic instructions …   Wikipedia

Share the article and excerpts

Direct link
Do a right-click on the link above
and select “Copy Link”