🚀 go-pugleaf

RetroBBS NetNews Server

Inspired by RockSolid Light RIP Retro Guy

Article View: comp.std.c++
Article #3514

Re: Q: default constructor for fundamental types?

#3514
From: Harlan Messinger
Date: Mon, 26 Feb 1996 20:13
69 lines
2576 bytes
Dirk Herrmann (dirk@sallust.ida.ing.tu-bs.de) wrote:
: Sorry if this has been discussed before.
: 
: When using templates, it appears that there should be
: default constructors for the fundamental data types.

Essentially, there is.

: 
: Example:
: 
: template <class T>
: X {
:   public:
:     X() : t() {};
:     X(const T& tt) : t(tt) {};
: 
:   private:
:     T t;
: }
: 
: As far as i know, the default constructor of
: e.g. X<int> would not compile since there is no default
: constructor for an int value.
: It seems to be a pity that this would not be allowed.

But it appears that it is allowed. It works fine in Visual C++ 2.2. 
There's are just two things: you left out the word "class" between "template 
<class T>" and the word "X"; and you need a semicolon after the closing 
right brace of the class definition.

The following produces output of "8" on the first line and gobbledygook 
on the second line, since the effect of the "default constructor" of the 
integer member function is to do nothing.

If your X class were only meant for numeric types, you could have the 
default constructor of X call the constructor for t as t(0) instead of 
t() if you always wanted default initialization to 0.

#include <iostream.h>

template <class T>
 X {
  public:
    X() : t() {};
    X(const T& tt) : t(tt) {};
	 void output() { cout << t << "\n"; }
  private:
 	T t;
};

int main() 
{
	X<int> i(8);
	X<int> j;
	i.output();
	j.output();
	int x;
	cin >> x; // Pause for input: this is a QuickWin program.
	return 0;
}


[ To submit articles: Try just posting with your newsreader.
		      If that fails, use mailto:std-c++@ncar.ucar.edu
  FAQ:    http://reality.sgi.com/employees/austern_mti/std-c++/faq.html
  Policy: http://reality.sgi.com/employees/austern_mti/std-c++/policy.html
  Comments? mailto:std-c++-request@ncar.ucar.edu
]
Technical Details
Message-ID: <4gsvhn$csi@clarknet.clark.net>
Path: arc1-ca.pugleaf.net!engnews1.Eng.Sun.COM!taumet!clamage
References: <4glrdc$dqo@ra.ibr.cs.tu-bs.de>

Show Full Headers
Complete Article Headers
Path: arc1-ca.pugleaf.net!engnews1.Eng.Sun.COM!taumet!clamage
From: gusty@clark.net (Harlan Messinger)
Newsgroups: comp.std.c++
Subject: Re: Q: default constructor for fundamental types?
Date: 26 Feb 1996 20:13:44 GMT
Organization: Clark Internet Services, Inc., Ellicott City, MD USA
Approved: clamage@eng.sun.com (comp.std.c++)
Message-ID: <4gsvhn$csi@clarknet.clark.net>
References: <4glrdc$dqo@ra.ibr.cs.tu-bs.de>
NNTP-Posting-Host: taumet.eng.sun.com
Mime-Version: 1.0
Content-Type: TEXT/PLAIN; charset=ISO-8859-1
Content-Transfer-Encoding: 8bit
X-Nntp-Posting-Host: explorer.clark.net
X-Newsreader: TIN [UNIX 1.3 950726BETA PL0]
Originator: clamage@taumet