473,670 Members | 2,683 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

When a default constructor necessary?

When a non-default constructor provided in a class, the default constructor
is not available anymore.

In what cases shall a default constructor be defined explicitly?

Specifically, in the following cases, shall a default constructor be
provided?
1. Inheritance. Class A is derived from class B. Shall a default constructor
be defined for A and B?

2. Virtual inheritance.

3. When class A contains class B, Shall a default constructor be defined for
A and B?

4. Abstract base class.

Thanks in advance!


Jul 22 '05 #1
17 2501
* highli:

in the following cases, shall a default constructor be provided?

1. Inheritance. Class A is derived from class B. Shall a default constructor
be defined for A and B?

2. Virtual inheritance.

3. When class A contains class B, Shall a default constructor be defined for
A and B?

4. Abstract base class.


Those possible reasons are _unrelated_ to whether a default constructor
should be defined.

Define a default constructor when there is natural default state.

--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
Jul 22 '05 #2

"highli" <hi****@cls.com > wrote in message
news:lD******** ************@bg tnsc05-news.ops.worldn et.att.net...
When a non-default constructor provided in a class, the default constructor is not available anymore.

In what cases shall a default constructor be defined explicitly?

Specifically, in the following cases, shall a default constructor be
provided?
1. Inheritance. Class A is derived from class B. Shall a default constructor be defined for A and B?

2. Virtual inheritance.

3. When class A contains class B, Shall a default constructor be defined for A and B?

4. Abstract base class.

Thanks in advance!


None of these absolutely require a default constructor assuming that you
have defined what a default constructor is. You can provide an alternate
constructor to satisfy all the above mentioned conditions just like you
might mix default constructors and alternate cstors to generate the end
product.

Whats important is that your derived class indicate which cstor is
appropriate to create base/members in its cstor's initialization list. Which
is critical since the base class(es) and member class(es) need to be
generated before the cstor of the derived class is invoked. You can't build
the house if you haven't poured the foundation.

If what you are asking is whether defining cstors are a requirement, the
answer is no, but since C++ gives the power to define creation, why not take
charge and control the process since that may help in the case of
tracing/debugging? Not to mention the fact that you only get what you want
with explicit invocations.

Incidentally, what you might want to spend more time on, is whether and what
copy cstor, as well as assignment operator you might need. Look up the
subject of "deep copy".
Jul 22 '05 #3
On Sat, 24 Jul 2004 22:44:33 GMT, highli <hi****@cls.com > wrote:
When a non-default constructor provided in a class, the default
constructor
is not available anymore.

In what cases shall a default constructor be defined explicitly?

When you want the default constructor to do something different from the
compiler generated default constructor or when you want a default
constructor and the compiler won't generate one for you for some reason.
Specifically, in the following cases, shall a default constructor be
provided?
1. Inheritance. Class A is derived from class B. Shall a default
constructor
be defined for A and B?

2. Virtual inheritance.

3. When class A contains class B, Shall a default constructor be defined
for
A and B?

4. Abstract base class.


None of these issues are relevant in any way that I can see.

john
Jul 22 '05 #4

"highli" <hi****@cls.com > wrote in message
news:lD******** ************@bg tnsc05-news.ops.worldn et.att.net...
When a non-default constructor provided in a class, the default constructor is not available anymore.

In what cases shall a default constructor be defined explicitly?


When you want to create an array of objects of your class. You can't do so
in the absence of a default constructor. Another reason to switch over to
std::vector which doesn't impose such a restriction.

-Sharad
Jul 22 '05 #5
* Sharad Kala:

"highli" <hi****@cls.com > wrote in message
news:lD******** ************@bg tnsc05-news.ops.worldn et.att.net...
When a non-default constructor provided in a class, the default constructor
is not available anymore.

In what cases shall a default constructor be defined explicitly?


When you want to create an array of objects of your class.


That's most often a Very Bad reason, because it most often adds an
unusable state. Use smart-pointers instead. E.g. boost::shared_p tr.

You can't do so in the absence of a default constructor.
I'm sure that "highli" can write e.g.

class Point
{
int myX, mY;
public:
Point( int x, u ): myX( x ), myY( y ) {}
int x() const { return x; }
int y() const { return y; }
};

Point const points[] =
{ Point( 1, 2 ), Point( 3, 4 ), Point( 5, 6 ) };

or some such, without thinking twice (or at least he or she will be able
to do this after a while).

Another reason to switch over to
std::vector which doesn't impose such a restriction.


It's not very clear what you mean here.

--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
Jul 22 '05 #6

"Alf P. Steinbach" <al***@start.no > wrote in message
news:41******** ********@news.i ndividual.net.. .
* Sharad Kala:

"highli" <hi****@cls.com > wrote in message
news:lD******** ************@bg tnsc05-news.ops.worldn et.att.net...
When a non-default constructor provided in a class, the default

constructor
is not available anymore.

In what cases shall a default constructor be defined explicitly?


When you want to create an array of objects of your class.


That's most often a Very Bad reason, because it most often adds an
unusable state. Use smart-pointers instead. E.g. boost::shared_p tr.


I was just mentioning one case when things can not be done without a default
constructor since it was not mentioned in any of the other replies. Not
recommending any way to do things.
You can't do so in the absence of a default constructor.

[snip]
Another reason to switch over to
std::vector which doesn't impose such a restriction.


It's not very clear what you mean here.

Read the FAQ - http://www.parashift.com/c++-faq-lit....html#faq-10.5

-Sharad

Jul 22 '05 #7
* Sharad Kala:

"Alf P. Steinbach" <al***@start.no > wrote in message
news:41******** ********@news.i ndividual.net.. .
* Sharad Kala:

"highli" <hi****@cls.com > wrote in message
news:lD******** ************@bg tnsc05-news.ops.worldn et.att.net...
> When a non-default constructor provided in a class, the default
constructor
> is not available anymore.
>
> In what cases shall a default constructor be defined explicitly?

When you want to create an array of objects of your class.


That's most often a Very Bad reason, because it most often adds an
unusable state. Use smart-pointers instead. E.g. boost::shared_p tr.


I was just mentioning one case when things can not be done without a default
constructor since it was not mentioned in any of the other replies. Not
recommending any way to do things.
You can't do so in the absence of a default constructor.

[snip]
Another reason to switch over to
std::vector which doesn't impose such a restriction.


It's not very clear what you mean here.


Read the FAQ - http://www.parashift.com/c++-faq-lit....html#faq-10.5


Thank you.

I'm CC'ing this to Marshall Cline; this FAQ item wasn't meant to create
the impression you got (note that at the very start it mentions "except
as discussed below"). In short, the correct version is that you can't
create an array of objects of a class type that has no default
constructor unless (a) an array initializer is given (the FAQ item gives
an example of that at the end, essentially the same example that I gave
and you snipped but without the typos... ;-) ), or (b) placement new is
used, as it is internally in std::vector. Point (b) should perhaps be
mentioned directly in this FAQ item, and both points placed at the top.

Now study the example at the _end_ of that FAQ item... ;-)

--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
Jul 22 '05 #8

"Alf P. Steinbach" <al***@start.no > wrote in message
news:41******** ********@news.i ndividual.net.. .
* Sharad Kala:
[snip] Read the FAQ -
http://www.parashift.com/c++-faq-lit....html#faq-10.5
Thank you.
Most welcome ;-)

I'm CC'ing this to Marshall Cline; this FAQ item wasn't meant to create
the impression you got (note that at the very start it mentions "except
I don't think I got a wrong impression. The very reason I snipped your
example was because you were correct in saying that I could still create an
array if I gave an initializer and _no_ default constructor. There was
nothing to nitpick there ;-) But still one needs to take the trouble to
initialize each member, isn't that a pain ?
as discussed below"). In short, the correct version is that you can't
create an array of objects of a class type that has no default
constructor unless (a) an array initializer is given (the FAQ item gives
an example of that at the end, essentially the same example that I gave
I think FAQ is correct here. It does say "except as discussed below" at the
start as you also point out.
and you snipped but without the typos... ;-) ), or (b) placement new is
used, as it is internally in std::vector. Point (b) should perhaps be
mentioned directly in this FAQ item, and both points placed at the top.


Do you mind giving one example of point b ?

-Sharad

Jul 22 '05 #9

"Alf P. Steinbach" <al***@start.no > wrote in message
news:41******** ********@news.i ndividual.net.. .
* Sharad Kala: [snip] It's a bit of work to do correctly. Modulo alignment issues and
exception issues and whatnot (omitted here... ;-) ) it goes like
Quite good but not quite ;-)
#include <new>

class Point{ ... };

int main()
{
size_t const nObjects = 54;
char memory[nObjects*sizeof ( Point )];
Point* pObjects = 0;

// Initialize array.
char *pMem = memory;
for( size_t i = 0; i < nObjects; ++i )
{
Point* pNew = ::new( pMem ) Point( i, -i ); // Whatever.
if( pObjects == 0 ) { pObjects = pNew; }
pMem += sizeof( Point );
}

// Use it.
// Whatever, e.g.
for( size_t i = 0; i < nObjects; ++i )
{
// std::cout << pObjects[i].x() << std::endl;
}
The following is not the way arrays would destruct.
// Destroy.
Point* pObj = pObjects;
for( size_t i = 0; i < nObjects; ++i, ++pObj )
{
pObject->~Point(); // Modulo syntax, check it out.
}

Instead something like -
// Destroy.
Point* pObj = pObjects + sizeof(nObjects *sizeof( Point ));
for( size_t i = 0; i < nObjects; ++i, --pObj )
{
pObjects->~Point(); // Modulo syntax, check it out.
}
Right, Alf ?

-Sharad
Jul 22 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
4964
by: Kutty Banerjee | last post by:
Hi, MyClass *myclass_=new MyClass; and MyClass::MyClass(int) and no default constructor. My object assignment obviously gives an error. So waht is the correct way to do it without using vectors of course. kutty
6
2475
by: pauldepstein | last post by:
I am reading Grimshaw and Ortega's "C++ and Numerical Methods." They construct a vector class which contains the variable vec, a float* variable where the length of the array (number of components in the vector) is given by the variable name veclength. That is what I _do_ understand. What I don't understand is the coding for the default constructor which includes vec=0; What does it mean for a pointer to be equal to 0? Presumably...
18
3116
by: lchian | last post by:
Hi, I have a vector of class Foo. When I do a push_back(), I expect stl to call the default constructor I wrote for Foo. But instead, stl makes up its own default that is initialized with garbage. Is there a way to force stl to use MY default constructor?
12
2693
by: Edward Diener | last post by:
Given value class X { public: // Not allowed: X():i(100000),s(10000) { } // Allowed void InitializeDefaults() { i = 100000; s = 10000; } private: int i;
9
3540
by: Alex Vinokur | last post by:
Compiler Green Hills C++, Version 4.0.6 --- foo.cpp --- struct A { }; struct B { B() {}
10
2965
by: Szabolcs Horvát | last post by:
Consider the attached example program: an object of type 'A' is inserted into a 'map<int, Am;'. Why does 'm;' call the copy constructor of 'A' twice in addition to a constructor call? The constructors and copy constructors in 'A' report when they are called. 'whoami' is just a unique identifier assigned to every object of type 'A'. The output of the program is: constructor 0 constructor 1
5
1908
by: subramanian100in | last post by:
Consider the program #include <iostream> #include <string> class A { public: void print(void) const; A(const std::string &s) : str(s) { }
43
3810
by: JohnQ | last post by:
Are a default constructor, destructor, copy constructor and assignment operator generated by the compiler for a struct if they are not explicitely defined? I think the answer is yes, because "there is no difference between a struct and a class except the public/private access specification" (and a few minor other things). When I create a class, I always start by declaring the default constructor, copy constructor and assignment operator...
5
359
by: * Tong * | last post by:
Hi, I couldn't figure out the answer myself about the default constructor -- does C++ create it by default? If yes, under what circumstances? Actually, I've found out the partial answer myself via trying the following code: ----------------------------------------- #include <string>
0
8468
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8386
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8901
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8814
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
7415
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6213
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4390
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2041
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1792
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.