473,398 Members | 2,368 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,398 software developers and data experts.

no default constructor -- bad form?

Hi,

I am writing a program and needs to know one of its object members
before it can be initialized. It doesn't really matter for my
question (which a C++ question, not a windows question), but the class
is used in a windows program and has an HWND member ( a handle to a
window), and to make an sense the class must know what the member is.

But this puts me in the position of having no default constructor, and
I've heard that is considered bad form. What is the right way to
handle this situation? Or is it okay to have a class which has no
default constructor?

I found one other thread on this subject in the archives, but I didn't
understand the solution proposed, which involved using the Factory
Design. I don't quite see how this solves the problem, and would love
an explanation of that, if it's relevant. (code is below)

Thanks for any help,
cpp

------BEGIN SNIPPET-----
I have come across many instances where it seems like a class
is most correctly encapsulated when there is NO default constructor.
E.g., I might end up with something like:

class A {
private:
const B& x_;
public:
A(const B& x) : x_(x) {}
// other stuff
};

In this example, I have to initialize x_ to something meaningful when
the class is constructed. More importantly, I want the constructor
to leave A in a valid state, where A is valid only if x_ is meaningfully
initialized (to something only the caller can determine).

How about a factory?

class A {
private:
A() : x_(sX) {};
static B& sX;
public:
static A* makeArrayOfA(const B&x, const long numA) { sX = x; return
new
A[numA];};
....
};

---------END SNIPPET----------


Jul 22 '05 #1
10 4846
On Sun, 02 May 2004 03:40:35 GMT, cppaddict <he***@hello.com> wrote:
Hi,

I am writing a program and needs to know one of its object members
before it can be initialized. It doesn't really matter for my
question (which a C++ question, not a windows question), but the class
is used in a windows program and has an HWND member ( a handle to a
window), and to make an sense the class must know what the member is.

But this puts me in the position of having no default constructor, and
I've heard that is considered bad form. What is the right way to
handle this situation? Or is it okay to have a class which has no
default constructor?


Someone says it is "bad form" not to have a default constructor? I don't
quite get it. Perhaps in some specific situation, but generally speaking,
classes where it makes no sense for them to be default-initialized are
better off without a default constructor...because of the very reason
you've hit upon: how do you initialize things that /need/ a value if you
don't have a value?

In courses I teach, there are often classes that represent bank accounts of
one type or another, with data members representing account holder's names,
the account number, etc. It wouldn't make a whole lot of sense to allow a
class such as that to be default-initialized.

Some situations where you'll run into trouble, however, are if you need to
create built-in arrays of such objects, or if you use an STL facility that
requires default initialization for the elements involved (for example, if
you use a std::vector, and use resize() to increase the number of elements
in the vector). Otherwise, I wouldn't feel guilty just because a class of
yours doesn't have a default constructor.
-leor

--
Leor Zolman --- BD Software --- www.bdsoft.com
On-Site Training in C/C++, Java, Perl and Unix
C++ users: download BD Software's free STL Error Message Decryptor at:
www.bdsoft.com/tools/stlfilt.html
Jul 22 '05 #2

"cppaddict" <he***@hello.com> wrote in message
news:d0********************************@4ax.com...
Hi,

I am writing a program and needs to know one of its object members
before it can be initialized. It doesn't really matter for my
question (which a C++ question, not a windows question), but the class
is used in a windows program and has an HWND member ( a handle to a
window), and to make an sense the class must know what the member is.

But this puts me in the position of having no default constructor, and
I've heard that is considered bad form. What is the right way to
handle this situation? Or is it okay to have a class which has no
default constructor?

If you don't have a default constructor then certain code using your class
won't compile, e.g. array declarations. So you should add a default
constructor if it can be done. But if it's really is nonsense to default
constructor then don't do so.
I found one other thread on this subject in the archives, but I didn't
understand the solution proposed, which involved using the Factory
Design. I don't quite see how this solves the problem, and would love
an explanation of that, if it's relevant. (code is below)

Thanks for any help,
cpp

------BEGIN SNIPPET-----
I have come across many instances where it seems like a class
is most correctly encapsulated when there is NO default constructor.
E.g., I might end up with something like:

class A {
private:
const B& x_;
public:
A(const B& x) : x_(x) {}
// other stuff
};

In this example, I have to initialize x_ to something meaningful when
the class is constructed. More importantly, I want the constructor
to leave A in a valid state, where A is valid only if x_ is meaningfully
initialized (to something only the caller can determine).

How about a factory?

class A {
private:
A() : x_(sX) {};
static B& sX;
public:
static A* makeArrayOfA(const B&x, const long numA) { sX = x; return
new
A[numA];};
...
};


The answer describes a way to create an array in the absence of a public
default constructor, which is not what your question was about.

john
Jul 22 '05 #3
"cppaddict" <he***@hello.com> wrote in message
news:d0********************************@4ax.com...
Hi,

I am writing a program and needs to know one of its object members
before it can be initialized. It doesn't really matter for my
question (which a C++ question, not a windows question), but the class
is used in a windows program and has an HWND member ( a handle to a
window), and to make an sense the class must know what the member is.

But this puts me in the position of having no default constructor, and
I've heard that is considered bad form. What is the right way to
handle this situation? Or is it okay to have a class which has no
default constructor?

I found one other thread on this subject in the archives, but I didn't
understand the solution proposed, which involved using the Factory
Design. I don't quite see how this solves the problem, and would love
an explanation of that, if it's relevant. (code is below)

Thanks for any help,
cpp


[snip the snippet]

I wouldn't base any aspect of my design on "hearing that such-and-such is
bad form". If you don't want or need a default constructor, don't put one
in.

However, there is some advantage to having a default constructor. For
instance it allows you to put members of your class into a container. Here
are a couple of workarounds.

1) Objects generally have states, and you can define an "uninitialized
state" which would be where your default constructor would leave it. A
method could then be called to complete your object's initialization when
you are ready.

However, this approach has its risks. You would have to consider how to
avoid the mistake of using an unitialized object and also what is going to
happen if you do. If this is more trouble than its worth, leaving out the
default constructor is probably better.

2) Reference counted smart pointers provide copy semantics which allow you
to put them in standard containers no matter what they point to. So:

#include <boost/shared_ptr.hpp>
#include <vector>

typedef PFred boost::shared_ptr<Fred>;
std::vector<PFred> a_vec;

a_vec.push_back(PFred(new Fred(some_argument));
a_vec.back()->fred_function();

<untested (==wrong) code>

If class "Fred" has no default constructor this will work even though
"std::vector<Fred> b_vec;" would not work.

--
Cy
http://home.rochester.rr.com/cyhome/
Jul 22 '05 #4

"Cy Edmunds" <ce******@spamless.rochester.rr.com> wrote in message
news:k3blc.135266>
However, this approach has its risks. You would have to consider how to
avoid the mistake of using an unitialized object and also what is going to
happen if you do. If this is more trouble than its worth, leaving out the
default constructor is probably better.


But won't leaving out the default constructor open you up to having the
compiler create one for you, in case someone *does* define an array of your
class (or otherwise declare an instance of your object such that the default
constructor would be called)? I think perhaps then it might be better to
make a default construtor, but make it private, wouldn't it?

-Howard
Jul 22 '05 #5

"Howard" <al*****@hotmail.com> wrote in message
news:c7********@dispatch.concentric.net...

"Cy Edmunds" <ce******@spamless.rochester.rr.com> wrote in message
news:k3blc.135266>
However, this approach has its risks. You would have to consider how to
avoid the mistake of using an unitialized object and also what is going to happen if you do. If this is more trouble than its worth, leaving out the default constructor is probably better.

But won't leaving out the default constructor open you up to having the
compiler create one for you, in case someone *does* define an array of

your class (or otherwise declare an instance of your object such that the default constructor would be called)? I think perhaps then it might be better to
make a default construtor, but make it private, wouldn't it?

-Howard


The compiler will create a default constructor only for classes which have
no other constructor.

john
Jul 22 '05 #6

"John Harrison" <jo*************@hotmail.com> wrote in message
news:c75uk4$3jme$1@ID->
The compiler will create a default constructor only for classes which have
no other constructor.

john


Ok, I see.

My compiler won't let me create an array unless I have a default constructor
(when there are other constructors present), so I know right away that I
either need to write one myself or not create an array like that. Thanks
for the clarification.

-Howard
Jul 22 '05 #7
Declare a private default constructor with no implementation (if your
compiler allows that, or an inline {} otherwise.)

This ensures that you have a known default construction, but no one will
ever use it. I often do this with copy constructors and operator= if I don't
want them being used.
"Howard" <al*****@hotmail.com> wrote in message
news:c7********@dispatch.concentric.net...

"Cy Edmunds" <ce******@spamless.rochester.rr.com> wrote in message
news:k3blc.135266>
However, this approach has its risks. You would have to consider how to
avoid the mistake of using an unitialized object and also what is going to happen if you do. If this is more trouble than its worth, leaving out the default constructor is probably better.

But won't leaving out the default constructor open you up to having the
compiler create one for you, in case someone *does* define an array of

your class (or otherwise declare an instance of your object such that the default constructor would be called)? I think perhaps then it might be better to
make a default construtor, but make it private, wouldn't it?

-Howard

Jul 22 '05 #8

Paul wrote:
Declare a private default constructor with no implementation (if your
compiler allows that, or an inline {} otherwise.)

This ensures that you have a known default construction, but no one will
ever use it. I often do this with copy constructors and operator= if I don't
want them being used.


Just to nitpick here: the latter cases are functionally valid - if you
don't supply the copy constructor and assignment operator, the compiler
will - the former is not - once you supply a non-default constructor,
you don't need to specifically create a dummy default constructor to
avoid it being used.

If you want to make a case for doing it for the sake of clarity, go
ahead. Personally, when i see a (non-pure virtual) declaration, i would
assume there is a definition somewhere (the two cases of the copy
constructor and assignment operator i mentioned above being the only
exceptions) - and i would be right peeved to go hunting all over hell
for it only to find it was a (needless) dummy declaration. On the other
hand, if i see a class declaration with a non-default constructor and no
default constructor, it's a pretty clear statement to me that the class
requires some kind of explicit initialization.

But i do have a question i'm curious about. If i were to write:

class Foo {
public:
Foo(const Foo&) {};
};

is Foo::Foo() generated automatically?

mark

Jul 22 '05 #9
"Mark A. Gibbs" <x_*********@rogers.com_x> wrote in message news:<L%**********************@twister01.bloor.is. net.cable.rogers.com>...
class Foo {
public:
Foo(const Foo&) {};
};

is Foo::Foo() generated automatically?

mark


No. An explicit constructor of any kind disables the automatic
generation of the default constructor.
Jul 22 '05 #10
al************@comcast.net (A. Lloyd Flanagan) wrote in message news:<e8**************************@posting.google. com>...

[ ... ]
No. An explicit constructor of any kind disables the automatic
generation of the default constructor.


Just to clarify something that could be misinterpreted here: in this
case, "explicit constructor" is referring to any constructor that is
not defined automatically. Use of the keyword "explicit" is not
what's at hand.
--
Later,
Jerry.

The universe is a figment of its own imagination.
Jul 22 '05 #11

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

Similar topics

14
by: Vinodh Kumar | last post by:
class A { int myIntVal; }; int main() { A a; return 0; }
15
by: A | last post by:
Hi, A default copy constructor is created for you when you don't specify one yourself. In such case, the default copy constructor will simply do a bitwise copy for primitives (including...
18
by: Matt | last post by:
I try to compare the default constructor in Java and C++. In C++, a default constructor has one of the two meansings 1) a constructor has ZERO parameter Student() { //etc... } 2) a...
0
by: - vhannak | last post by:
I have Visual Studio C# app where the main form keeps a log of the application's status. For several of the event handlers and methods in the main form, I have try/catch blocks. But adding...
19
by: Andrew J. Marshall | last post by:
I want to create a class that must receive a parameter when instantiated. In other words, I do not want it to have a "Public Sub New()". 1) Does VB.NET create a default public constructor if I do...
10
by: Joel | last post by:
Is it true that if we don't specify a default constructor for our class, then the C# compiler provides us with its own that zeroes (or assigns default values) to the data members? I wrote a...
74
by: Zytan | last post by:
I have a struct constructor to initialize all of my private (or public readonly) fields. There still exists the default constructor that sets them all to zero. Is there a way to remove the...
23
by: Jess | last post by:
Hello, I understand the default-initialization happens if we don't initialize an object explicitly. I think for an object of a class type, the value is determined by the constructor, and for...
4
by: Jess | last post by:
Hello, I tried several books to find out the details of object initialization. Unfortunately, I'm still confused by two specific concepts, namely default-initialization and...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...
0
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...
0
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,...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
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,...

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.