Default constructor

In computer programming languages, the term default constructor can refer to a constructor that is automatically generated by the compiler in the absence of any programmer-defined constructors (e.g. in Java), and is usually a nullary constructor. In other languages (e.g. in C++) it is a constructor that can be called without having to provide any arguments, irrespective of whether the constructor is auto-generated or user-defined. Note that a constructor with formal parameters can still be called without arguments if default arguments were provided in the constructor's definition.

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
{
public:
    MyClass();  // constructor declared

private:
    int x;
};

MyClass::MyClass() : x(100)  // constructor defined
{
}

int main()
{
    MyClass m;  // at runtime, object m is created, and the default constructor is called
}

When allocating memory dynamically, the constructor may be called by adding parenthesis after the class name. In a sense, this is an explicit call to the constructor:

int main()
{
    MyClass * pointer = new MyClass();  // at runtime, an object is created, and the
                                        // default constructor is called
}

If the constructor does have one or more parameters, but they all have default values, then it is still a default constructor. Remember that each class can have at most one default constructor, either one without parameters, or one whose all parameters have default values, such as in this case:

class MyClass
{
public:
    MyClass (int i = 0, std::string s = "");  // constructor declared

private:
    int x;
    int y;
    std::string z;
};

MyClass::MyClass(int i, std::string s)     // constructor defined
{
    x = 100;
    y = i;
    z = s;
}

In C++, default constructors are significant because they are automatically invoked in certain circumstances; and therefore, in these circumstances, it is an error for a class to not have a default constructor:

  • 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; or new MyClass();), the default constructor of MyClass 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 of MyClass 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 ten elements, which are filled with a default-constructed MyClass object.

If a class has no explicitly defined constructors, the compiler will implicitly declare and define a default constructor for it. This implicitly defined default constructor is equivalent to an explicitly defined one with an empty body. For example:[2]

class MyClass
{
    int x;  // no constructor, so the compiler produces an (implicit) default constructor
};

int main()
{
    MyClass m;   // no error at runtime: the (implicit) default constructor is called
}

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.

class MyClass
{
public:
    MyClass (int y);  // declaration a non-default constructor

private:
    int x;
};

MyClass::MyClass (int y)
{
    x = y;
}

int main()
{
    MyClass m(100);     // the non-default constructor is called
    MyClass * p;        // for pointer declarations, the compiler does not need to know about constructors
    p = new MyClass();  // error at compilation: no default constructor
    return 0;
}

Since neither the programmer nor the compiler has defined a default constructor, the creation of the objected pointed to by p leads to an error.[3]

On the other hand in C++11 a default constructor can be explicitly created:

class MyClass
{
public:
    MyClass () = default;  // force generation of a default constructor
};

Or explicitly inhibited:

class MyClass
{
public:
    MyClass () = delete;  // prevent generation of default constructor
};

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 implicitly calls the superclass's nullary constructor, then executes an empty body. All fields are left at their initial value of 0 (integer types), 0.0 (floating-point types), false (boolean type), or null (reference types). A programmer-defined constructor that takes no parameters is also called a default constructor in C#, but not in Java.[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)

Read other articles:

العلاقات الأفغانية المكسيكية أفغانستان المكسيك   أفغانستان   المكسيك تعديل مصدري - تعديل   العلاقات الأفغانية المكسيكية هي العلاقات الثنائية التي تجمع بين أفغانستان والمكسيك.[1][2][3][4][5] مقارنة بين البلدين هذه مقارنة عامة ومرجعية للدولتين:...

 

Ayub 18Kitab Ayub lengkap pada Kodeks Leningrad, dibuat tahun 1008.KitabKitab AyubKategoriKetuvimBagian Alkitab KristenPerjanjian LamaUrutan dalamKitab Kristen18← pasal 17 pasal 19 → Ayub 18 (disingkat Ayb 18) adalah bagian dari Kitab Ayub di Alkitab Ibrani dan Perjanjian Lama dalam Alkitab Kristen. Kitab ini menceritakan riwayat Ayub, seorang yang saleh, dan pencobaan yang dialaminya.[1][2] Teks Naskah sumber utama: Masoretik, Septuaginta dan Naskah Laut Mati. Pas...

 

For Norman Cook's other recordings, see Norman Cook discography. Fatboy Slim discographyCook performing at the 2013 Glastonbury Festival.Studio albums4Live albums3Compilation albums2Video albums3Music videos31EPs5Singles28Soundtrack albums1Remix albums3Mix albums6 The discography of Fatboy Slim, an alias of Norman Cook, an English DJ, big beat musician, and record producer, consists of four studio albums, three live albums, one soundtrack album, two compilation albums, three remix albums, si...

У этого термина существуют и другие значения, см. Кубок (значения). Кубок Ку́бок[1] (др.-греч. κύβος) — сосуд для питья вина, пива, мёда или медовухи. Чаще всего металлический, но нередко делался из кости или стекла, украшался орнаментом и драгоценными камнями. В средневек...

 

Questa voce sull'argomento centri abitati del Mato Grosso è solo un abbozzo. Contribuisci a migliorarla secondo le convenzioni di Wikipedia. CuiabácomuneMunicípio de Cuiabá Cuiabá – Veduta LocalizzazioneStato Brasile Stato federato Mato Grosso MesoregioneCentro-Sul Mato-Grossense MicroregioneCuiabá AmministrazioneSindacoEmanuel Pinheiro Data di istituzione1719 TerritorioCoordinate15°35′31″S 56°06′09″W / 15.591944°S 56.1025°W-15.591944; -56.10...

 

† Человек прямоходящий Научная классификация Домен:ЭукариотыЦарство:ЖивотныеПодцарство:ЭуметазоиБез ранга:Двусторонне-симметричныеБез ранга:ВторичноротыеТип:ХордовыеПодтип:ПозвоночныеИнфратип:ЧелюстноротыеНадкласс:ЧетвероногиеКлада:АмниотыКлада:Синапсиды�...

1946 1956 Élections législatives de 1951 dans l'Aube le 17 juin 1951 Type d’élection Élection législative Postes à élire 4 députés modifier - modifier le code - voir Wikidata  Les élections législatives françaises de 1951 se tiennent le 17 juin. Ce sont les deuxièmes élections législatives de la Quatrième République. Mode de Scrutin Représentation proportionnelle plurinominale suivant la méthode du plus fort reste dans 103 circonscriptions, conformément à la ...

 

Proposed US supersonic airliner design This article includes a list of references, related reading, or external links, but its sources remain unclear because it lacks inline citations. Please help improve this article by introducing more precise citations. (April 2009) (Learn how and when to remove this message) Lockheed L-2000 Full-scale mockup of the L-2000-7 design Role Supersonic airlinerType of aircraft Manufacturer Lockheed Corporation Status Canceled in 1971 The Lockheed L-2000 was Loc...

 

For other uses, see Mahdia (disambiguation). Place in Mahdia Governorate, TunisiaMahdia المهديةClockwise from top: Mahdia Museum, the Great Mosque of Mahdia, the port of Mahdia, a street in Mahdia, the Skifa al-Kahla. SealMahdiaLocation in TunisiaCoordinates: 35°30′N 11°04′E / 35.500°N 11.067°E / 35.500; 11.067Country TunisiaGovernorateMahdia GovernorateDelegation(s)MahdiaGovernment • MayorFaiza Boubaker Belkhir (Independent) Population&...

Эта статья — о спортивном сооружении в Берлине. О местности в Рейнланд-Пфальце см. Майфельд. Вид на Олимпийский стадион со стороны Майского поля. Фото 2012 года Расположение Майского поля на карте Колокольня и трибуна на Майском поле перед стадионом. Фото 2017...

 

Arma letale 3Martin Riggs (Mel Gibson) in una scena del filmTitolo originaleLethal Weapon 3 Paese di produzioneStati Uniti d'America Anno1992 Durata118 min Rapporto2,39:1 Genereazione, commedia, poliziesco RegiaRichard Donner SoggettoJeffrey Boam (personaggi creati da Shane Black) SceneggiaturaJeffrey Boam, Robert Mark Kamen ProduttoreJoel Silver, Richard Donner Casa di produzioneWarner Bros., Silver Pictures Distribuzione in italianoWarner Bros. Italia FotografiaJan de Bont Montaggio...

 

British Army general Sir Colin McVean GubbinsSir Colin Gubbins c.1940sBorn(1896-07-02)2 July 1896Tokyo, JapanDied11 February 1976(1976-02-11) (aged 79)Stornoway, Lewis, ScotlandAllegianceUnited KingdomService/branchBritish ArmyYears of service1914–1946RankMajor-GeneralService number14618UnitRoyal Field ArtilleryCommands held24th Guards Brigade (1940)Auxiliary Units (1940)Special Operations Executive (1943–1946)Battles/warsFirst World WarNorth Russia CampaignAnglo-Irish WarSecond...

For other people with the same name, see James Anderson. Part of a series onFreemasonry Overview Grand Lodge Masonic lodge Masonic lodge officers Grand Master Prince Hall Freemasonry Regular Masonic jurisdiction Anglo-American Freemasonry Continental Freemasonry History History of Freemasonry Liberté chérie Masonic manuscripts Masonic bodies Masonic Masonic bodies York Rite Order of Mark Master Masons Holy Royal Arch Royal Arch Masonry Cryptic Masonry Knights Templar Red Cross of Constantin...

 

مرحلة النزاع المبكر من الحرب الأهلية السورية جزء من الحرب الأهلية السورية نقطة تفتيش للجيش العربي السوري في دوما، يناير 2012 معلومات عامة التاريخ 29 يوليو 2011 – 20 أبريل 2012(8 أشهرٍ و22 يومًا) من أسبابها محاولة المعارضة لقلب نظام الحكم السوري البعثي الموقع سوريا، البلدان المجاور...

 

Brazilian football club Football clubCaxias Full nameCaxias Futebol ClubeNickname(s)GualichoAlvinegroFoundedOctober 12, 1920 (103 years ago) (1920-10-12)GroundErnestão, Joinville (SC)Capacity5,000WebsiteClub website Home colours Away colours Caxias Futebol Clube is a Brazilian football club based in Joinville, with a population of more than half a million the largest city of the south Brazilian state of Santa Catarina. The club, founded on October 12, 1920, won in the years 192...

President of Zimbabwe since 2017 Emmerson MnangagwaOfficial portrait, 20173rd President of ZimbabweIncumbentAssumed office 24 November 2017Vice PresidentConstantino ChiwengaKembo MohadiPreceded byRobert MugabePresident and First Secretary of ZANU-PFIncumbentAssumed office 19 November 2017Preceded byRobert MugabeFirst Vice-President of ZimbabweIn office12 December 2014 – 6 November 2017PresidentRobert MugabePreceded byJoice MujuruSucceeded byConstantino ChiwengaMinister ...

 

Sistem koordinat sferis biasa digunakan dalam fisika. Ini memberikan tiga angka (dikenal sebagai koordinat) untuk setiap titik dalam ruang Euklides: jarak radial r, sudut kutub θ (theta), dan sudut azimut φ (phi). Simbol ρ (rho) sering digunakan sebagai pengganti r. Dalam geometri, sistem koordinat adalah suatu sistem yang menggunakan satu atau lebih bilangan, atau koordinat, untuk secara unik menentukan posisi suatu titik atau unsur geometris lain pada manifold seperti ruang Euklides.[...

 

Institutional corruption in the country Political corruption Forms and concepts Bribery Cronyism Economics of corruption Electoral fraud Elite capture Influence peddling Kleptocracy Mafia state Nepotism Pyrrhic defeat theory Slush fund Simony State capture State-corporate crime Throffer Anti-corruption International Anti-Corruption Court Group of States Against Corruption International Anti-Corruption Academy International Anti-Corruption Day United Nations Convention against Corruption Corru...

1965 novel by Ivan Southall Ash Road First editionAuthorIvan SouthallIllustratorClem SealeLanguageEnglishGenrechildren's fictionPublisherAngus and RobertsonPublication date1965Publication placeAustraliaMedia typePrintPages154pp Ash Road (1965) is a novel for children by Australian author Ivan Southall. It won the Children's Book of the Year Award: Older Readers in 1966.[1] Plot outline Three fifteen-year-old boys are for the first time allowed to go on a holiday together without ...

 

Pour les articles homonymes, voir Victory Road. Logo de Victory Road 2012 Victory Road est un pay-per-view de catch organisé par la Total Nonstop Action Wrestling. C'était le premier gros PPV d'une durée de trois heures de la TNA qui s'est déroulé en novembre 2004 et sera toujours considéré comme un évènement important dans l'histoire de la TNA. En 2006, il devenait un PPV annuel au mois de juillet. Événement # Événement Date Ville Arène Main Event Temps 1 Victory Road (2004) 7...